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
108 * @throws JSONException
110 public JSONObject convertToJsonSchema(final Module module, final SchemaContext schemaContext) throws IOException, JSONException {
111 final JSONObject models = new JSONObject();
112 models.put(UNIQUE_EMPTY_IDENTIFIER, new JSONObject());
113 topLevelModule = module;
114 processModules(module, models, schemaContext);
115 processContainersAndLists(module, models, schemaContext);
116 processRPCs(module, models, schemaContext);
117 processIdentities(module, models);
121 private void processModules(final Module module, final JSONObject models, final SchemaContext schemaContext) throws JSONException {
122 createConcreteModelForPost(models, module.getName() + BaseYangSwaggerGenerator.MODULE_NAME_SUFFIX,
123 createPropertiesForPost(module, schemaContext, module.getName()));
126 private void processContainersAndLists(final Module module, final JSONObject models, final SchemaContext schemaContext)
127 throws IOException, JSONException {
128 final String moduleName = module.getName();
130 for (final DataSchemaNode childNode : module.getChildNodes()) {
131 // For every container and list in the module
132 if (childNode instanceof ContainerSchemaNode || childNode instanceof ListSchemaNode) {
133 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, true, schemaContext);
134 processDataNodeContainer((DataNodeContainer) childNode, moduleName, models, false, schemaContext);
140 * Process the RPCs for a Module Spits out a file each of the name <rpcName>-input.json and <rpcName>-output.json
141 * for each RPC that contains input & output elements
144 * @throws JSONException
145 * @throws IOException
147 private void processRPCs(final Module module, final JSONObject models, final SchemaContext schemaContext) throws JSONException,
149 final Set<RpcDefinition> rpcs = module.getRpcs();
150 final String moduleName = module.getName();
151 for (final RpcDefinition rpc : rpcs) {
152 final ContainerSchemaNode input = rpc.getInput();
153 if (input !=null && input.getChildNodes() != null &&
154 !input.getChildNodes().isEmpty()) {
155 final JSONObject properties = processChildren(input.getChildNodes(), moduleName, models, true, schemaContext);
157 final String filename = "(" + rpc.getQName().getLocalName() + ")input";
158 final JSONObject childSchema = getSchemaTemplate();
159 childSchema.put(TYPE_KEY, OBJECT_TYPE);
160 childSchema.put(PROPERTIES_KEY, properties);
161 childSchema.put(ID_KEY, filename);
162 models.put(filename, childSchema);
164 processTopData(filename, models, input);
167 final ContainerSchemaNode output = rpc.getOutput();
168 if (output !=null && output.getChildNodes() != null &&
169 !output.getChildNodes().isEmpty()) {
170 final JSONObject properties = processChildren(output.getChildNodes(), moduleName, models, true, schemaContext);
171 final String filename = "(" + rpc.getQName().getLocalName() + ")output";
172 final JSONObject childSchema = getSchemaTemplate();
173 childSchema.put(TYPE_KEY, OBJECT_TYPE);
174 childSchema.put(PROPERTIES_KEY, properties);
175 childSchema.put(ID_KEY, filename);
176 models.put(filename, childSchema);
178 processTopData(filename, models, output);
183 private JSONObject processTopData(final String filename, final JSONObject models, final SchemaNode schemaNode) {
184 final JSONObject items = new JSONObject();
186 items.put(REF_KEY, filename);
187 final JSONObject dataNodeProperties = new JSONObject();
188 dataNodeProperties.put(TYPE_KEY, schemaNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
189 dataNodeProperties.put(ITEMS_KEY, items);
191 dataNodeProperties.putOpt(DESCRIPTION_KEY, schemaNode.getDescription());
192 final JSONObject properties = new JSONObject();
193 properties.put(topLevelModule.getName() + ":" + schemaNode.getQName().getLocalName(), dataNodeProperties);
194 final JSONObject finalChildSchema = getSchemaTemplate();
195 finalChildSchema.put(TYPE_KEY, OBJECT_TYPE);
196 finalChildSchema.put(PROPERTIES_KEY, properties);
197 finalChildSchema.put(ID_KEY, filename + OperationBuilder.TOP);
198 models.put(filename + OperationBuilder.TOP, finalChildSchema);
200 return dataNodeProperties;
204 * Processes the 'identity' statement in a yang model and maps it to a 'model' in the Swagger JSON spec.
206 * @param module The module from which the identity stmt will be processed
207 * @param models The JSONObject in which the parsed identity will be put as a 'model' obj
209 private static void processIdentities(final Module module, final JSONObject models) throws JSONException {
211 final String moduleName = module.getName();
212 final Set<IdentitySchemaNode> idNodes = module.getIdentities();
213 LOG.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
215 for (final IdentitySchemaNode idNode : idNodes) {
216 final JSONObject identityObj = new JSONObject();
217 final String identityName = idNode.getQName().getLocalName();
218 LOG.debug("Processing Identity: {}", identityName);
220 identityObj.put(ID_KEY, identityName);
221 identityObj.put(DESCRIPTION_KEY, idNode.getDescription());
223 final JSONObject props = new JSONObject();
224 final IdentitySchemaNode baseId = idNode.getBaseIdentity();
226 if (baseId == null) {
228 * This is a base identity. So lets see if it has sub types. If it does, then add them to the model
231 final Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
233 if (derivedIds != null) {
234 final JSONArray subTypes = new JSONArray();
235 for (final IdentitySchemaNode derivedId : derivedIds) {
236 subTypes.put(derivedId.getQName().getLocalName());
238 identityObj.put(SUB_TYPES_KEY, subTypes);
243 * This is a derived entity. Add it's base type & move on.
245 props.put(TYPE_KEY, baseId.getQName().getLocalName());
248 // Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
249 identityObj.put(PROPERTIES_KEY, props);
250 models.put(identityName, identityObj);
254 private JSONObject processDataNodeContainer(final DataNodeContainer dataNode, final String parentName, final JSONObject models,
255 final boolean isConfig, final SchemaContext schemaContext) throws JSONException, IOException {
256 if (dataNode instanceof ListSchemaNode || dataNode instanceof ContainerSchemaNode) {
257 final Iterable<DataSchemaNode> containerChildren = dataNode.getChildNodes();
258 final String localName = ((SchemaNode) dataNode).getQName().getLocalName();
259 final JSONObject properties = processChildren(containerChildren, parentName + "/" + localName, models, isConfig, schemaContext);
260 final String nodeName = parentName + (isConfig ? OperationBuilder.CONFIG : OperationBuilder.OPERATIONAL)
263 final JSONObject childSchema = getSchemaTemplate();
264 childSchema.put(TYPE_KEY, OBJECT_TYPE);
265 childSchema.put(PROPERTIES_KEY, properties);
267 childSchema.put(ID_KEY, nodeName);
268 models.put(nodeName, childSchema);
271 createConcreteModelForPost(models, localName,
272 createPropertiesForPost(dataNode, schemaContext, parentName + "/" + localName));
275 return processTopData(nodeName, models, (SchemaNode) dataNode);
280 private static void createConcreteModelForPost(final JSONObject models, final String localName,
281 final JSONObject properties) throws JSONException {
282 final String nodePostName = OperationBuilder.CONFIG + localName + Post.METHOD_NAME;
283 final JSONObject postSchema = getSchemaTemplate();
284 postSchema.put(TYPE_KEY, OBJECT_TYPE);
285 postSchema.put(ID_KEY, nodePostName);
286 postSchema.put(PROPERTIES_KEY, properties);
287 models.put(nodePostName, postSchema);
290 private JSONObject createPropertiesForPost(final DataNodeContainer dataNodeContainer, final SchemaContext schemaContext, final String parentName)
291 throws JSONException {
292 final JSONObject properties = new JSONObject();
293 for (final DataSchemaNode childNode : dataNodeContainer.getChildNodes()) {
294 if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) {
295 final JSONObject items = new JSONObject();
296 items.put(REF_KEY, parentName + "(config)" + childNode.getQName().getLocalName());
297 final JSONObject property = new JSONObject();
298 property.put(TYPE_KEY, childNode instanceof ListSchemaNode ? ARRAY_TYPE : OBJECT_TYPE);
299 property.put(ITEMS_KEY, items);
300 properties.put(childNode.getQName().getLocalName(), property);
301 } else if (childNode instanceof LeafSchemaNode) {
302 final JSONObject property = processLeafNode((LeafSchemaNode) childNode, schemaContext);
303 properties.put(childNode.getQName().getLocalName(), property);
310 * Processes the nodes.
312 private JSONObject processChildren(final Iterable<DataSchemaNode> nodes, final String parentName, final JSONObject models,
313 final boolean isConfig, final SchemaContext schemaContext)
314 throws JSONException, IOException {
315 final JSONObject properties = new JSONObject();
316 for (final DataSchemaNode node : nodes) {
317 if (node.isConfiguration() == isConfig) {
318 final String name = resolveNodesName(node, topLevelModule, schemaContext);
319 final JSONObject property;
320 if (node instanceof LeafSchemaNode) {
321 property = processLeafNode((LeafSchemaNode) node, schemaContext);
323 } else if (node instanceof ListSchemaNode) {
324 property = processDataNodeContainer((ListSchemaNode) node, parentName, models, isConfig,
327 } else if (node instanceof LeafListSchemaNode) {
328 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
330 } else if (node instanceof ChoiceSchemaNode) {
331 if (((ChoiceSchemaNode) node).getCases().iterator().hasNext()) {
332 processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(),
333 parentName, models, schemaContext, isConfig, properties);
337 } else if (node instanceof AnyXmlSchemaNode) {
338 property = processAnyXMLNode((AnyXmlSchemaNode) node);
340 } else if (node instanceof ContainerSchemaNode) {
341 property = processDataNodeContainer((ContainerSchemaNode) node, parentName, models, isConfig,
345 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
347 property.putOpt(DESCRIPTION_KEY, node.getDescription());
348 properties.put(topLevelModule.getName() + ":" + name, property);
354 private JSONObject processLeafListNode(final LeafListSchemaNode listNode, final SchemaContext schemaContext) throws JSONException {
355 final JSONObject props = new JSONObject();
356 props.put(TYPE_KEY, ARRAY_TYPE);
358 final JSONObject itemsVal = new JSONObject();
359 final ConstraintDefinition constraints = listNode.getConstraints();
360 final Optional<Integer> maxOptional = Optional.fromNullable(constraints.getMaxElements());
361 if (maxOptional.or(2) >= 2) {
362 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
363 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
365 processTypeDef(listNode.getType(), listNode, itemsVal, schemaContext);
367 props.put(ITEMS_KEY, itemsVal);
370 processConstraints(constraints, props);
375 private void processChoiceNode(final Iterable<DataSchemaNode> nodes, final String moduleName, final JSONObject models,
376 final SchemaContext schemaContext, final boolean isConfig, final JSONObject properties)
377 throws JSONException, IOException {
378 for (final DataSchemaNode node : nodes) {
379 final String name = resolveNodesName(node, topLevelModule, schemaContext);
380 final JSONObject property;
382 if (node instanceof LeafSchemaNode) {
383 property = processLeafNode((LeafSchemaNode) node, schemaContext);
385 } else if (node instanceof ListSchemaNode) {
386 property = processDataNodeContainer((ListSchemaNode) node, moduleName, models, isConfig,
389 } else if (node instanceof LeafListSchemaNode) {
390 property = processLeafListNode((LeafListSchemaNode) node, schemaContext);
392 } else if (node instanceof ChoiceSchemaNode) {
393 if (((ChoiceSchemaNode) node).getCases().iterator().hasNext())
394 processChoiceNode(((ChoiceSchemaNode) node).getCases().iterator().next().getChildNodes(),
395 moduleName, models, schemaContext, isConfig, properties);
398 } else if (node instanceof AnyXmlSchemaNode) {
399 property = processAnyXMLNode((AnyXmlSchemaNode) node);
401 } else if (node instanceof ContainerSchemaNode) {
402 property = processDataNodeContainer((ContainerSchemaNode) node, moduleName, models, isConfig,
406 throw new IllegalArgumentException("Unknown DataSchemaNode type: " + node.getClass());
409 property.putOpt(DESCRIPTION_KEY, node.getDescription());
410 properties.put(name, property);
414 private static void processConstraints(final ConstraintDefinition constraints, final JSONObject props) throws JSONException {
415 final boolean isMandatory = constraints.isMandatory();
416 props.put(REQUIRED_KEY, isMandatory);
418 final Integer minElements = constraints.getMinElements();
419 final Integer maxElements = constraints.getMaxElements();
420 if (minElements != null) {
421 props.put(MIN_ITEMS, minElements);
423 if (maxElements != null) {
424 props.put(MAX_ITEMS, maxElements);
428 private JSONObject processLeafNode(final LeafSchemaNode leafNode, final SchemaContext schemaContext) throws JSONException {
429 final JSONObject property = new JSONObject();
431 final String leafDescription = leafNode.getDescription();
432 property.put(DESCRIPTION_KEY, leafDescription);
433 processConstraints(leafNode.getConstraints(), property);
434 processTypeDef(leafNode.getType(), leafNode, property, schemaContext);
439 private static JSONObject processAnyXMLNode(final AnyXmlSchemaNode leafNode) throws JSONException {
440 final JSONObject property = new JSONObject();
442 final String leafDescription = leafNode.getDescription();
443 property.put(DESCRIPTION_KEY, leafDescription);
445 processConstraints(leafNode.getConstraints(), property);
446 final String localName = leafNode.getQName().getLocalName();
447 property.put(TYPE_KEY, "example of anyxml " + localName);
452 private String processTypeDef(final TypeDefinition<?> leafTypeDef, final DataSchemaNode node,
453 final JSONObject property, final SchemaContext schemaContext) throws JSONException {
454 final String jsonType;
455 if (leafTypeDef.getDefaultValue() == null) {
456 if (leafTypeDef instanceof BinaryTypeDefinition) {
457 jsonType = processBinaryType(property);
459 } else if (leafTypeDef instanceof BitsTypeDefinition) {
460 jsonType = processBitsType((BitsTypeDefinition) leafTypeDef, property);
462 } else if (leafTypeDef instanceof EnumTypeDefinition) {
463 jsonType = processEnumType((EnumTypeDefinition) leafTypeDef, property);
465 } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
466 final String name = topLevelModule.getName();
467 jsonType = name + ":" + ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName();
469 } else if (leafTypeDef instanceof StringTypeDefinition) {
470 jsonType = processStringType(leafTypeDef, property, node.getQName().getLocalName());
472 } else if (leafTypeDef instanceof UnionTypeDefinition) {
473 jsonType = processUnionType((UnionTypeDefinition) leafTypeDef, property, schemaContext, node);
475 } else if (leafTypeDef instanceof EmptyTypeDefinition) {
476 jsonType = UNIQUE_EMPTY_IDENTIFIER;
478 } else if (leafTypeDef instanceof LeafrefTypeDefinition) {
479 return processLeafRef(node, property, schemaContext, leafTypeDef);
481 } else if (leafTypeDef instanceof BooleanTypeDefinition) {
484 } else if (leafTypeDef instanceof DecimalTypeDefinition) {
485 jsonType = String.valueOf(((DecimalTypeDefinition) leafTypeDef).getRangeConstraints()
486 .iterator().next().getMin());
488 } else if (leafTypeDef instanceof IntegerTypeDefinition) {
489 jsonType = String.valueOf(((IntegerTypeDefinition) leafTypeDef).getRangeConstraints()
490 .iterator().next().getMin());
492 } else if (leafTypeDef instanceof UnsignedIntegerTypeDefinition) {
493 jsonType = String.valueOf(((UnsignedIntegerTypeDefinition) leafTypeDef).getRangeConstraints()
494 .iterator().next().getMin());
497 jsonType = OBJECT_TYPE;
501 jsonType = String.valueOf(leafTypeDef.getDefaultValue());
503 property.putOpt(TYPE_KEY, jsonType);
507 private String processLeafRef(final DataSchemaNode node, final JSONObject property, final SchemaContext schemaContext,
508 final TypeDefinition<?> leafTypeDef) {
509 RevisionAwareXPath xPath = ((LeafrefTypeDefinition) leafTypeDef).getPathStatement();
510 final SchemaNode schemaNode;
512 final String xPathString = STRIP_PATTERN.matcher(xPath.toString()).replaceAll("");
513 xPath = new RevisionAwareXPathImpl(xPathString, xPath.isAbsolute());
516 if (xPath.isAbsolute()) {
517 module = findModule(schemaContext, leafTypeDef.getQName());
518 schemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xPath);
520 module = findModule(schemaContext, node.getQName());
521 schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xPath);
524 return processTypeDef(((TypedSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode, property, schemaContext);
527 private static Module findModule(final SchemaContext schemaContext, final QName qName) {
528 return schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(), qName.getRevision());
531 private static String processBinaryType(final JSONObject property) throws JSONException {
532 final JSONObject media = new JSONObject();
533 media.put(BINARY_ENCODING_KEY, BASE_64);
534 property.put(MEDIA_KEY, media);
538 private static String processEnumType(final EnumTypeDefinition enumLeafType, final JSONObject property) throws JSONException {
539 final List<EnumPair> enumPairs = enumLeafType.getValues();
540 final List<String> enumNames = new ArrayList<>();
541 for (final EnumPair enumPair : enumPairs) {
542 enumNames.add(enumPair.getName());
545 property.putOpt(ENUM, new JSONArray(enumNames));
546 return enumLeafType.getValues().iterator().next().getName();
549 private static String processBitsType(final BitsTypeDefinition bitsType, final JSONObject property) throws JSONException {
550 property.put(MIN_ITEMS, 0);
551 property.put(UNIQUE_ITEMS_KEY, true);
552 final List<String> enumNames = new ArrayList<>();
553 final List<Bit> bits = bitsType.getBits();
554 for (final Bit bit : bits) {
555 enumNames.add(bit.getName());
557 property.put(ENUM, new JSONArray(enumNames));
559 return enumNames.iterator().next() + " " + enumNames.get(enumNames.size() - 1);
562 private static String processStringType(final TypeDefinition<?> stringType, final JSONObject property, final String nodeName)
563 throws JSONException {
564 StringTypeDefinition type = (StringTypeDefinition) stringType;
565 List<LengthConstraint> lengthConstraints = ((StringTypeDefinition) stringType).getLengthConstraints();
566 while (lengthConstraints.isEmpty() && type.getBaseType() != null) {
567 type = type.getBaseType();
568 lengthConstraints = type.getLengthConstraints();
571 // FIXME: json-schema is not expressive enough to capture min/max laternatives. We should find the true minimum
572 // and true maximum implied by the constraints and use that.
573 for (final LengthConstraint lengthConstraint : lengthConstraints) {
574 final Number min = lengthConstraint.getMin();
575 final Number max = lengthConstraint.getMax();
576 property.putOpt(MIN_LENGTH_KEY, min);
577 property.putOpt(MAX_LENGTH_KEY, max);
579 if (type.getPatternConstraints().iterator().hasNext()) {
580 final PatternConstraint pattern = type.getPatternConstraints().iterator().next();
581 String regex = pattern.getRegularExpression();
582 regex = regex.substring(1, regex.length() - 1);
583 final Generex generex = new Generex(regex);
584 return generex.random();
586 return "Some " + nodeName;
590 private String processUnionType(final UnionTypeDefinition unionType, final JSONObject property,
591 final SchemaContext schemaContext, final DataSchemaNode node)
592 throws JSONException {
593 final List<String> unionNames = new ArrayList<>();
594 for (final TypeDefinition<?> typeDef : unionType.getTypes()) {
595 unionNames.add(processTypeDef(typeDef, node, property, schemaContext));
597 property.put(ENUM, new JSONArray(unionNames));
598 return unionNames.iterator().next();
602 * Helper method to generate a pre-filled JSON schema object.
604 private static JSONObject getSchemaTemplate() throws JSONException {
605 final JSONObject schemaJSON = new JSONObject();
606 schemaJSON.put(SCHEMA_KEY, SCHEMA_URL);