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.NullNode;
16 import com.fasterxml.jackson.databind.node.ObjectNode;
17 import com.fasterxml.jackson.databind.node.TextNode;
18 import com.mifmif.common.regex.Generex;
19 import java.io.IOException;
20 import java.util.List;
22 import java.util.regex.Pattern;
23 import javax.annotation.concurrent.NotThreadSafe;
24 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
25 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
30 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.Module;
38 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
39 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
47 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
52 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
56 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
57 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
61 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
66 * Generates JSON Schema for data defined in YANG.
69 public class ModelGenerator {
71 private static final Logger LOG = LoggerFactory.getLogger(ModelGenerator.class);
73 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
74 private static final String BASE_64 = "base64";
75 private static final String BINARY_ENCODING_KEY = "binaryEncoding";
76 private static final String MEDIA_KEY = "media";
77 private static final String UNIQUE_ITEMS_KEY = "uniqueItems";
78 private static final String MAX_ITEMS = "maxItems";
79 private static final String MIN_ITEMS = "minItems";
80 private static final String SCHEMA_URL = "http://json-schema.org/draft-04/schema";
81 private static final String SCHEMA_KEY = "$schema";
82 private static final String MAX_LENGTH_KEY = "maxLength";
83 private static final String MIN_LENGTH_KEY = "minLength";
84 private static final String REQUIRED_KEY = "required";
85 private static final String REF_KEY = "$ref";
86 private static final String ITEMS_KEY = "items";
87 private static final String TYPE_KEY = "type";
88 private static final String PROPERTIES_KEY = "properties";
89 private static final String DESCRIPTION_KEY = "description";
90 private static final String OBJECT_TYPE = "object";
91 private static final String ARRAY_TYPE = "array";
92 private static final String ENUM = "enum";
93 private static final String ID_KEY = "id";
94 private static final String SUB_TYPES_KEY = "subTypes";
95 private static final String UNIQUE_EMPTY_IDENTIFIER = "unique_empty_identifier";
97 private Module topLevelModule;
99 public ModelGenerator() {
103 * Creates Json models from provided module according to swagger spec.
105 * @param module - Yang module to be converted
106 * @param schemaContext - SchemaContext of all Yang files used by Api Doc
107 * @return ObjectNode containing data used for creating examples and models in Api Doc
108 * @throws IOException if I/O operation fails
110 public ObjectNode convertToJsonSchema(final Module module,
111 final SchemaContext schemaContext) throws IOException {
112 final ObjectNode models = JsonNodeFactory.instance.objectNode();
113 models.put(UNIQUE_EMPTY_IDENTIFIER, NullNode.getInstance());
114 topLevelModule = module;
115 processModules(module, models, schemaContext);
116 processContainersAndLists(module, models, schemaContext);
117 processRPCs(module, models, schemaContext);
118 processIdentities(module, models);
122 private void processModules(final Module module, final ObjectNode models,
123 final SchemaContext schemaContext) {
124 createConcreteModelForPost(models, module.getName() + BaseYangSwaggerGenerator.MODULE_NAME_SUFFIX,
125 createPropertiesForPost(module, schemaContext, module.getName()));
128 private void processContainersAndLists(final Module module, final ObjectNode models,
129 final SchemaContext schemaContext) throws IOException {
130 final String moduleName = module.getName();
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);
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.
146 * @param module module
147 * @throws IOException if I/O operation fails
149 private void processRPCs(final Module module, final ObjectNode models,
150 final SchemaContext schemaContext) throws IOException {
151 final Set<RpcDefinition> rpcs = module.getRpcs();
152 final String moduleName = module.getName();
153 for (final RpcDefinition rpc : rpcs) {
154 final ContainerSchemaNode input = rpc.getInput();
155 if (!input.getChildNodes().isEmpty()) {
156 final ObjectNode properties =
157 processChildren(input.getChildNodes(), moduleName, models, true, schemaContext);
159 final String filename = "(" + rpc.getQName().getLocalName() + ")input";
160 final ObjectNode childSchema = getSchemaTemplate();
161 childSchema.put(TYPE_KEY, OBJECT_TYPE);
162 childSchema.put(PROPERTIES_KEY, properties);
163 childSchema.put(ID_KEY, filename);
164 models.put(filename, childSchema);
166 processTopData(filename, models, input);
169 final ContainerSchemaNode output = rpc.getOutput();
170 if (!output.getChildNodes().isEmpty()) {
171 final ObjectNode properties =
172 processChildren(output.getChildNodes(), moduleName, models, true, schemaContext);
173 final String filename = "(" + rpc.getQName().getLocalName() + ")output";
174 final ObjectNode childSchema = getSchemaTemplate();
175 childSchema.put(TYPE_KEY, OBJECT_TYPE);
176 childSchema.put(PROPERTIES_KEY, properties);
177 childSchema.put(ID_KEY, filename);
178 models.put(filename, childSchema);
180 processTopData(filename, models, output);
185 private ObjectNode processTopData(final String filename, final ObjectNode models, final SchemaNode schemaNode) {
186 final ObjectNode items = JsonNodeFactory.instance.objectNode();
188 items.put(REF_KEY, filename);
189 final ObjectNode dataNodeProperties = JsonNodeFactory.instance.objectNode();
190 dataNodeProperties.put(TYPE_KEY, schemaNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
191 dataNodeProperties.put(ITEMS_KEY, items);
193 putIfNonNull(dataNodeProperties, DESCRIPTION_KEY, schemaNode.getDescription());
194 final ObjectNode properties = JsonNodeFactory.instance.objectNode();
195 properties.put(topLevelModule.getName() + ":" + schemaNode.getQName().getLocalName(), dataNodeProperties);
196 final ObjectNode finalChildSchema = getSchemaTemplate();
197 finalChildSchema.put(TYPE_KEY, OBJECT_TYPE);
198 finalChildSchema.put(PROPERTIES_KEY, properties);
199 finalChildSchema.put(ID_KEY, filename + OperationBuilder.TOP);
200 models.put(filename + OperationBuilder.TOP, finalChildSchema);
202 return dataNodeProperties;
206 * Processes the 'identity' statement in a yang model and maps it to a 'model' in the Swagger JSON spec.
208 * @param module The module from which the identity stmt will be processed
209 * @param models The ObjectNode in which the parsed identity will be put as a 'model' obj
211 private static void processIdentities(final Module module, final ObjectNode models) {
213 final String moduleName = module.getName();
214 final Set<IdentitySchemaNode> idNodes = module.getIdentities();
215 LOG.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
217 for (final IdentitySchemaNode idNode : idNodes) {
218 final ObjectNode identityObj = JsonNodeFactory.instance.objectNode();
219 final String identityName = idNode.getQName().getLocalName();
220 LOG.debug("Processing Identity: {}", identityName);
222 identityObj.put(ID_KEY, identityName);
223 putIfNonNull(identityObj, DESCRIPTION_KEY, idNode.getDescription());
225 final ObjectNode props = JsonNodeFactory.instance.objectNode();
226 final IdentitySchemaNode baseId = idNode.getBaseIdentity();
228 if (baseId == null) {
230 * This is a base identity. So lets see if it has sub types. If it does, then add them to the model
233 final Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
235 if (derivedIds != null) {
236 final ArrayNode subTypes = new ArrayNode(JsonNodeFactory.instance);
237 for (final IdentitySchemaNode derivedId : derivedIds) {
238 subTypes.add(derivedId.getQName().getLocalName());
240 identityObj.put(SUB_TYPES_KEY, subTypes);
245 * This is a derived entity. Add it's base type & move on.
247 props.put(TYPE_KEY, baseId.getQName().getLocalName());
250 // Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
251 identityObj.put(PROPERTIES_KEY, props);
252 models.put(identityName, identityObj);
256 private ObjectNode processDataNodeContainer(
257 final DataNodeContainer dataNode, final String parentName, final ObjectNode models, final boolean isConfig,
258 final SchemaContext schemaContext) throws IOException {
259 if (dataNode instanceof ListSchemaNode || dataNode instanceof ContainerSchemaNode) {
260 final Iterable<DataSchemaNode> containerChildren = dataNode.getChildNodes();
261 final String localName = ((SchemaNode) dataNode).getQName().getLocalName();
262 final ObjectNode properties =
263 processChildren(containerChildren, parentName + "/" + localName, models, isConfig, schemaContext);
264 final String nodeName = parentName + (isConfig ? OperationBuilder.CONFIG : OperationBuilder.OPERATIONAL)
267 final ObjectNode childSchema = getSchemaTemplate();
268 childSchema.put(TYPE_KEY, OBJECT_TYPE);
269 childSchema.put(PROPERTIES_KEY, properties);
271 childSchema.put(ID_KEY, nodeName);
272 models.put(nodeName, childSchema);
275 createConcreteModelForPost(models, localName,
276 createPropertiesForPost(dataNode, schemaContext, parentName + "/" + localName));
279 return processTopData(nodeName, models, (SchemaNode) dataNode);
284 private static void createConcreteModelForPost(final ObjectNode models, final String localName,
285 final JsonNode properties) {
286 final String nodePostName = OperationBuilder.CONFIG + localName + Post.METHOD_NAME;
287 final ObjectNode postSchema = getSchemaTemplate();
288 postSchema.put(TYPE_KEY, OBJECT_TYPE);
289 postSchema.put(ID_KEY, nodePostName);
290 postSchema.put(PROPERTIES_KEY, properties);
291 models.put(nodePostName, postSchema);
294 private JsonNode createPropertiesForPost(final DataNodeContainer dataNodeContainer,
295 final SchemaContext schemaContext, final String parentName) {
296 final ObjectNode properties = JsonNodeFactory.instance.objectNode();
297 for (final DataSchemaNode childNode : dataNodeContainer.getChildNodes()) {
298 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
299 final ObjectNode items = JsonNodeFactory.instance.objectNode();
300 items.put(REF_KEY, parentName + "(config)" + childNode.getQName().getLocalName());
301 final ObjectNode property = JsonNodeFactory.instance.objectNode();
302 property.put(TYPE_KEY, childNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
303 property.put(ITEMS_KEY, items);
304 properties.put(childNode.getQName().getLocalName(), property);
305 } else if (childNode instanceof LeafSchemaNode) {
306 final ObjectNode property = processLeafNode((LeafSchemaNode) childNode, schemaContext);
307 properties.put(childNode.getQName().getLocalName(), property);
314 * Processes the nodes.
316 private ObjectNode processChildren(
317 final Iterable<DataSchemaNode> nodes, final String parentName, final ObjectNode models,
318 final boolean isConfig, final SchemaContext schemaContext) throws IOException {
319 final ObjectNode properties = JsonNodeFactory.instance.objectNode();
320 for (final DataSchemaNode node : nodes) {
321 if (node.isConfiguration() == isConfig) {
322 final String name = resolveNodesName(node, topLevelModule, schemaContext);
323 final ObjectNode property;
324 if (node instanceof LeafSchemaNode) {
325 property = processLeafNode((LeafSchemaNode) node, schemaContext);
327 } else if (node instanceof ListSchemaNode) {
328 property = processDataNodeContainer((ListSchemaNode) node, parentName, models, isConfig,
331 } else if (node instanceof LeafListSchemaNode) {
332 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
334 } else if (node instanceof ChoiceSchemaNode) {
335 if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) {
336 processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(),
337 parentName, models, schemaContext, isConfig, properties);
341 } else if (node instanceof AnyXmlSchemaNode) {
342 property = processAnyXMLNode((AnyXmlSchemaNode) node);
344 } else if (node instanceof ContainerSchemaNode) {
345 property = processDataNodeContainer((ContainerSchemaNode) node, parentName, models, isConfig,
349 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
351 putIfNonNull(property, DESCRIPTION_KEY, node.getDescription());
352 properties.put(topLevelModule.getName() + ":" + name, property);
358 private ObjectNode processLeafListNode(final LeafListSchemaNode listNode,
359 final SchemaContext schemaContext) {
360 final ObjectNode props = JsonNodeFactory.instance.objectNode();
361 props.put(TYPE_KEY, ARRAY_TYPE);
363 final ObjectNode itemsVal = JsonNodeFactory.instance.objectNode();
364 final ConstraintDefinition constraints = listNode.getConstraints();
365 int max = constraints.getMaxElements() == null ? 2 : constraints.getMaxElements();
367 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
368 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
370 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
372 props.put(ITEMS_KEY, itemsVal);
375 processConstraints(constraints, props);
380 private void processChoiceNode(
381 final Iterable<DataSchemaNode> nodes, final String moduleName, final ObjectNode models,
382 final SchemaContext schemaContext, final boolean isConfig, final ObjectNode properties)
384 for (final DataSchemaNode node : nodes) {
385 final String name = resolveNodesName(node, topLevelModule, schemaContext);
386 final ObjectNode property;
388 if (node instanceof LeafSchemaNode) {
389 property = processLeafNode((LeafSchemaNode) node, schemaContext);
391 } else if (node instanceof ListSchemaNode) {
392 property = processDataNodeContainer((ListSchemaNode) node, moduleName, models, isConfig,
395 } else if (node instanceof LeafListSchemaNode) {
396 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
398 } else if (node instanceof ChoiceSchemaNode) {
399 if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) {
400 processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(),
401 moduleName, models, schemaContext, isConfig, properties);
405 } else if (node instanceof AnyXmlSchemaNode) {
406 property = processAnyXMLNode((AnyXmlSchemaNode) node);
408 } else if (node instanceof ContainerSchemaNode) {
409 property = processDataNodeContainer((ContainerSchemaNode) node, moduleName, models, isConfig,
413 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
416 putIfNonNull(property, DESCRIPTION_KEY, node.getDescription());
417 properties.put(name, property);
421 private static void processConstraints(final ConstraintDefinition constraints,
422 final ObjectNode props) {
423 final boolean isMandatory = constraints.isMandatory();
424 props.put(REQUIRED_KEY, isMandatory);
426 final Integer minElements = constraints.getMinElements();
427 final Integer maxElements = constraints.getMaxElements();
428 if (minElements != null) {
429 props.put(MIN_ITEMS, minElements);
431 if (maxElements != null) {
432 props.put(MAX_ITEMS, maxElements);
436 private ObjectNode processLeafNode(final LeafSchemaNode leafNode,
437 final SchemaContext schemaContext) {
438 final ObjectNode property = JsonNodeFactory.instance.objectNode();
440 final String leafDescription = leafNode.getDescription();
441 putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
442 processConstraints(leafNode.getConstraints(), property);
443 processTypeDef(leafNode.getType(), leafNode, property, schemaContext);
448 private static ObjectNode processAnyXMLNode(final AnyXmlSchemaNode leafNode) {
449 final ObjectNode property = JsonNodeFactory.instance.objectNode();
451 final String leafDescription = leafNode.getDescription();
452 putIfNonNull(property, DESCRIPTION_KEY, leafDescription);
454 processConstraints(leafNode.getConstraints(), property);
455 final String localName = leafNode.getQName().getLocalName();
456 property.put(TYPE_KEY, "example of anyxml " + localName);
461 private String processTypeDef(final TypeDefinition<?> leafTypeDef, final DataSchemaNode node,
462 final ObjectNode property, final SchemaContext schemaContext) {
463 final String jsonType;
464 if (leafTypeDef.getDefaultValue() == null) {
465 if (leafTypeDef instanceof BinaryTypeDefinition) {
466 jsonType = processBinaryType(property);
468 } else if (leafTypeDef instanceof BitsTypeDefinition) {
469 jsonType = processBitsType((BitsTypeDefinition) leafTypeDef, property);
471 } else if (leafTypeDef instanceof EnumTypeDefinition) {
472 jsonType = processEnumType((EnumTypeDefinition) leafTypeDef, property);
474 } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
475 final String name = topLevelModule.getName();
477 name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName();
479 } else if (leafTypeDef instanceof StringTypeDefinition) {
480 jsonType = processStringType(leafTypeDef, property, node.getQName().getLocalName());
482 } else if (leafTypeDef instanceof UnionTypeDefinition) {
483 jsonType = processUnionType((UnionTypeDefinition) leafTypeDef, property, schemaContext, node);
485 } else if (leafTypeDef instanceof EmptyTypeDefinition) {
486 jsonType = UNIQUE_EMPTY_IDENTIFIER;
488 } else if (leafTypeDef instanceof LeafrefTypeDefinition) {
489 return processLeafRef(node, property, schemaContext, leafTypeDef);
491 } else if (leafTypeDef instanceof BooleanTypeDefinition) {
494 } else if (leafTypeDef instanceof DecimalTypeDefinition) {
495 jsonType = String.valueOf(((DecimalTypeDefinition) leafTypeDef).getRangeConstraints()
496 .iterator().next().getMin());
498 } else if (leafTypeDef instanceof IntegerTypeDefinition) {
499 jsonType = String.valueOf(((IntegerTypeDefinition) leafTypeDef).getRangeConstraints()
500 .iterator().next().getMin());
502 } else if (leafTypeDef instanceof UnsignedIntegerTypeDefinition) {
503 jsonType = String.valueOf(((UnsignedIntegerTypeDefinition) leafTypeDef).getRangeConstraints()
504 .iterator().next().getMin());
507 jsonType = OBJECT_TYPE;
511 jsonType = String.valueOf(leafTypeDef.getDefaultValue());
513 putIfNonNull(property, TYPE_KEY, jsonType);
517 private String processLeafRef(final DataSchemaNode node, final ObjectNode property,
518 final SchemaContext schemaContext, final TypeDefinition<?> leafTypeDef) {
519 RevisionAwareXPath xpath = ((LeafrefTypeDefinition) leafTypeDef).getPathStatement();
520 final SchemaNode schemaNode;
522 final String xPathString = STRIP_PATTERN.matcher(xpath.toString()).replaceAll("");
523 xpath = new RevisionAwareXPathImpl(xPathString, xpath.isAbsolute());
526 if (xpath.isAbsolute()) {
527 module = findModule(schemaContext, leafTypeDef.getQName());
528 schemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xpath);
530 module = findModule(schemaContext, node.getQName());
531 schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xpath);
534 return processTypeDef(((TypedSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode,
535 property, schemaContext);
538 private static Module findModule(final SchemaContext schemaContext, final QName qualifiedName) {
540 .findModuleByNamespaceAndRevision(qualifiedName.getNamespace(), qualifiedName.getRevision());
543 private static String processBinaryType(final ObjectNode property) {
544 final ObjectNode media = JsonNodeFactory.instance.objectNode();
545 media.put(BINARY_ENCODING_KEY, BASE_64);
546 property.put(MEDIA_KEY, media);
550 private static String processEnumType(final EnumTypeDefinition enumLeafType,
551 final ObjectNode property) {
552 final List<EnumPair> enumPairs = enumLeafType.getValues();
553 ArrayNode enumNames = new ArrayNode(JsonNodeFactory.instance);
554 for (final EnumPair enumPair : enumPairs) {
555 enumNames.add(new TextNode(enumPair.getName()));
558 property.put(ENUM, enumNames);
559 return enumLeafType.getValues().iterator().next().getName();
562 private static String processBitsType(final BitsTypeDefinition bitsType,
563 final ObjectNode property) {
564 property.put(MIN_ITEMS, 0);
565 property.put(UNIQUE_ITEMS_KEY, true);
566 ArrayNode enumNames = new ArrayNode(JsonNodeFactory.instance);
567 final List<Bit> bits = bitsType.getBits();
568 for (final Bit bit : bits) {
569 enumNames.add(new TextNode(bit.getName()));
571 property.put(ENUM, enumNames);
573 return enumNames.iterator().next() + " " + enumNames.get(enumNames.size() - 1);
576 private static String processStringType(final TypeDefinition<?> stringType,
577 final ObjectNode property, final String nodeName) {
578 StringTypeDefinition type = (StringTypeDefinition) stringType;
579 List<LengthConstraint> lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraints();
580 while (lengthConstraints.isEmpty() && type.getBaseType() != null) {
581 type = type.getBaseType();
582 lengthConstraints = type.getLengthConstraints();
585 // FIXME: json-schema is not expressive enough to capture min/max laternatives. We should find the true minimum
586 // and true maximum implied by the constraints and use that.
587 for (final LengthConstraint lengthConstraint : lengthConstraints) {
588 final Number min = lengthConstraint.getMin();
589 final Number max = lengthConstraint.getMax();
590 putIfNonNull(property, MIN_LENGTH_KEY, min);
591 putIfNonNull(property, MAX_LENGTH_KEY, max);
593 if (type.getPatternConstraints().iterator().hasNext()) {
594 final PatternConstraint pattern = type.getPatternConstraints().iterator().next();
595 String regex = pattern.getRegularExpression();
596 regex = regex.substring(1, regex.length() - 1);
597 final Generex generex = new Generex(regex);
598 return generex.random();
600 return "Some " + nodeName;
604 private String processUnionType(final UnionTypeDefinition unionType, final ObjectNode property,
605 final SchemaContext schemaContext, final DataSchemaNode node) {
606 final ArrayNode unionNames = new ArrayNode(JsonNodeFactory.instance);
607 for (final TypeDefinition<?> typeDef : unionType.getTypes()) {
608 unionNames.add(processTypeDef(typeDef, node, property, schemaContext));
610 property.put(ENUM, unionNames);
611 return unionNames.iterator().next().asText();
615 * Helper method to generate a pre-filled JSON schema object.
617 private static ObjectNode getSchemaTemplate() {
618 final ObjectNode schemaJSON = JsonNodeFactory.instance.objectNode();
619 schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);
624 private static void putIfNonNull(ObjectNode property, String key, Number number) {
625 if (key != null && number != null) {
626 if (number instanceof Double) {
627 property.put(key, (Double) number);
628 } else if (number instanceof Float) {
629 property.put(key, (Float) number);
630 } else if (number instanceof Integer) {
631 property.put(key, (Integer) number);
632 } else if (number instanceof Short) {
633 property.put(key, (Short) number);
634 } else if (number instanceof Long) {
635 property.put(key, (Long) number);
640 private static void putIfNonNull(ObjectNode property, String key, String value) {
641 if (key != null && value != null) {
642 property.put(key, value);