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.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;
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;
65 * Generates JSON Schema for data defined in YANG.
68 public class ModelGenerator {
70 private static final Logger LOG = LoggerFactory.getLogger(ModelGenerator.class);
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";
96 private Module topLevelModule;
98 public ModelGenerator() {
102 * Creates Json models from provided module according to swagger spec.
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
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);
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()));
128 private void processContainersAndLists(final Module module, final JSONObject models,
129 final SchemaContext schemaContext) throws IOException, JSONException {
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 JSONException when things are amiss
148 * @throws IOException if I/O operation fails
150 private void processRPCs(final Module module, final JSONObject models,
151 final SchemaContext schemaContext) throws JSONException,
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);
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);
168 processTopData(filename, models, input);
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);
182 processTopData(filename, models, output);
187 private JSONObject processTopData(final String filename, final JSONObject models, final SchemaNode schemaNode) {
188 final JSONObject items = new JSONObject();
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);
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);
204 return dataNodeProperties;
208 * Processes the 'identity' statement in a yang model and maps it to a 'model' in the Swagger JSON spec.
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
213 private static void processIdentities(final Module module, final JSONObject models) throws JSONException {
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());
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);
224 identityObj.put(ID_KEY, identityName);
225 identityObj.put(DESCRIPTION_KEY, idNode.getDescription());
227 final JSONObject props = new JSONObject();
228 final IdentitySchemaNode baseId = idNode.getBaseIdentity();
230 if (baseId == null) {
232 * This is a base identity. So lets see if it has sub types. If it does, then add them to the model
235 final Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
237 if (derivedIds != null) {
238 final JSONArray subTypes = new JSONArray();
239 for (final IdentitySchemaNode derivedId : derivedIds) {
240 subTypes.put(derivedId.getQName().getLocalName());
242 identityObj.put(SUB_TYPES_KEY, subTypes);
247 * This is a derived entity. Add it's base type & move on.
249 props.put(TYPE_KEY, baseId.getQName().getLocalName());
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);
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)
269 final JSONObject childSchema = getSchemaTemplate();
270 childSchema.put(TYPE_KEY, OBJECT_TYPE);
271 childSchema.put(PROPERTIES_KEY, properties);
273 childSchema.put(ID_KEY, nodeName);
274 models.put(nodeName, childSchema);
277 createConcreteModelForPost(models, localName,
278 createPropertiesForPost(dataNode, schemaContext, parentName + "/" + localName));
281 return processTopData(nodeName, models, (SchemaNode) dataNode);
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);
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);
317 * Processes the nodes.
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);
331 } else if (node instanceof ListSchemaNode) {
332 property = processDataNodeContainer((ListSchemaNode) node, parentName, models, isConfig,
335 } else if (node instanceof LeafListSchemaNode) {
336 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
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);
345 } else if (node instanceof AnyXmlSchemaNode) {
346 property = processAnyXMLNode((AnyXmlSchemaNode) node);
348 } else if (node instanceof ContainerSchemaNode) {
349 property = processDataNodeContainer((ContainerSchemaNode) node, parentName, models, isConfig,
353 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
355 property.putOpt(DESCRIPTION_KEY, node.getDescription());
356 properties.put(topLevelModule.getName() + ":" + name, property);
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);
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);
374 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
376 props.put(ITEMS_KEY, itemsVal);
379 processConstraints(constraints, props);
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;
392 if (node instanceof LeafSchemaNode) {
393 property = processLeafNode((LeafSchemaNode) node, schemaContext);
395 } else if (node instanceof ListSchemaNode) {
396 property = processDataNodeContainer((ListSchemaNode) node, moduleName, models, isConfig,
399 } else if (node instanceof LeafListSchemaNode) {
400 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
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);
409 } else if (node instanceof AnyXmlSchemaNode) {
410 property = processAnyXMLNode((AnyXmlSchemaNode) node);
412 } else if (node instanceof ContainerSchemaNode) {
413 property = processDataNodeContainer((ContainerSchemaNode) node, moduleName, models, isConfig,
417 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
420 property.putOpt(DESCRIPTION_KEY, node.getDescription());
421 properties.put(name, property);
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);
430 final Integer minElements = constraints.getMinElements();
431 final Integer maxElements = constraints.getMaxElements();
432 if (minElements != null) {
433 props.put(MIN_ITEMS, minElements);
435 if (maxElements != null) {
436 props.put(MAX_ITEMS, maxElements);
440 private JSONObject processLeafNode(final LeafSchemaNode leafNode,
441 final SchemaContext schemaContext) throws JSONException {
442 final JSONObject property = new JSONObject();
444 final String leafDescription = leafNode.getDescription();
445 property.put(DESCRIPTION_KEY, leafDescription);
446 processConstraints(leafNode.getConstraints(), property);
447 processTypeDef(leafNode.getType(), leafNode, property, schemaContext);
452 private static JSONObject processAnyXMLNode(final AnyXmlSchemaNode leafNode) throws JSONException {
453 final JSONObject property = new JSONObject();
455 final String leafDescription = leafNode.getDescription();
456 property.put(DESCRIPTION_KEY, leafDescription);
458 processConstraints(leafNode.getConstraints(), property);
459 final String localName = leafNode.getQName().getLocalName();
460 property.put(TYPE_KEY, "example of anyxml " + localName);
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);
472 } else if (leafTypeDef instanceof BitsTypeDefinition) {
473 jsonType = processBitsType((BitsTypeDefinition) leafTypeDef, property);
475 } else if (leafTypeDef instanceof EnumTypeDefinition) {
476 jsonType = processEnumType((EnumTypeDefinition) leafTypeDef, property);
478 } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
479 final String name = topLevelModule.getName();
481 name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName();
483 } else if (leafTypeDef instanceof StringTypeDefinition) {
484 jsonType = processStringType(leafTypeDef, property, node.getQName().getLocalName());
486 } else if (leafTypeDef instanceof UnionTypeDefinition) {
487 jsonType = processUnionType((UnionTypeDefinition) leafTypeDef, property, schemaContext, node);
489 } else if (leafTypeDef instanceof EmptyTypeDefinition) {
490 jsonType = UNIQUE_EMPTY_IDENTIFIER;
492 } else if (leafTypeDef instanceof LeafrefTypeDefinition) {
493 return processLeafRef(node, property, schemaContext, leafTypeDef);
495 } else if (leafTypeDef instanceof BooleanTypeDefinition) {
498 } else if (leafTypeDef instanceof DecimalTypeDefinition) {
499 jsonType = String.valueOf(((DecimalTypeDefinition) leafTypeDef).getRangeConstraints()
500 .iterator().next().getMin());
502 } else if (leafTypeDef instanceof IntegerTypeDefinition) {
503 jsonType = String.valueOf(((IntegerTypeDefinition) leafTypeDef).getRangeConstraints()
504 .iterator().next().getMin());
506 } else if (leafTypeDef instanceof UnsignedIntegerTypeDefinition) {
507 jsonType = String.valueOf(((UnsignedIntegerTypeDefinition) leafTypeDef).getRangeConstraints()
508 .iterator().next().getMin());
511 jsonType = OBJECT_TYPE;
515 jsonType = String.valueOf(leafTypeDef.getDefaultValue());
517 property.putOpt(TYPE_KEY, jsonType);
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;
526 final String xPathString = STRIP_PATTERN.matcher(xpath.toString()).replaceAll("");
527 xpath = new RevisionAwareXPathImpl(xPathString, xpath.isAbsolute());
530 if (xpath.isAbsolute()) {
531 module = findModule(schemaContext, leafTypeDef.getQName());
532 schemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xpath);
534 module = findModule(schemaContext, node.getQName());
535 schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xpath);
538 return processTypeDef(((TypedSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode,
539 property, schemaContext);
542 private static Module findModule(final SchemaContext schemaContext, final QName qualifiedName) {
544 .findModuleByNamespaceAndRevision(qualifiedName.getNamespace(), qualifiedName.getRevision());
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);
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());
562 property.putOpt(ENUM, new JSONArray(enumNames));
563 return enumLeafType.getValues().iterator().next().getName();
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());
575 property.put(ENUM, new JSONArray(enumNames));
577 return enumNames.iterator().next() + " " + enumNames.get(enumNames.size() - 1);
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();
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);
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();
605 return "Some " + nodeName;
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));
616 property.put(ENUM, new JSONArray(unionNames));
617 return unionNames.iterator().next();
621 * Helper method to generate a pre-filled JSON schema object.
623 private static JSONObject getSchemaTemplate() throws JSONException {
624 final JSONObject schemaJSON = new JSONObject();
625 schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);