2 * Copyright (c) 2017 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
9 package org.opendaylight.mdsal.binding.javav2.generator.impl;
11 import static com.google.common.base.Preconditions.checkArgument;
12 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
13 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.replacePackageTopNamespace;
14 import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.BOOLEAN;
16 import com.google.common.annotations.Beta;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Splitter;
19 import com.google.common.base.Strings;
20 import com.google.common.collect.Iterables;
21 import java.util.Collection;
22 import java.util.List;
25 import java.util.regex.Pattern;
26 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForModule;
27 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForNode;
28 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForNodes;
29 import org.opendaylight.mdsal.binding.javav2.generator.impl.util.YangTextTemplate;
30 import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
31 import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil;
32 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier;
33 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer;
34 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
35 import org.opendaylight.mdsal.binding.javav2.generator.util.YangSnippetCleaner;
36 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
37 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
38 import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl;
39 import org.opendaylight.mdsal.binding.javav2.model.api.Constant;
40 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
41 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder;
42 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder;
43 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
44 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder;
45 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase;
46 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder;
47 import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
48 import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
51 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
57 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
58 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.Status;
62 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
70 * Auxiliary util class for {@link GenHelperUtil} class
73 final class AuxiliaryGenUtils {
75 private static final Splitter BSDOT_SPLITTER = Splitter.on(".");
76 private static final char NEW_LINE = '\n';
77 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
80 * Constant with the concrete name of identifier.
82 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
85 * Constant with the concrete name of namespace.
87 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
89 private AuxiliaryGenUtils() {
90 throw new UnsupportedOperationException("Util class");
93 static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
94 if (status == Status.DEPRECATED) {
95 builder.addAnnotation("", "Deprecated");
99 public static boolean hasBuilderClass(final SchemaNode schemaNode, final BindingNamespaceType namespaceType) {
100 return (namespaceType.equals(BindingNamespaceType.Data)
101 && (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
102 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition
103 || schemaNode instanceof ChoiceCaseNode));
106 static Constant qNameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
108 return toBuilder.addConstant(Types.typeForClass(QName.class), constantName, name);
112 * Created a method signature builder as part of
113 * <code>interfaceBuilder</code>.
115 * The method signature builder is created for the getter method of
116 * <code>schemaNodeName</code>. Also <code>comment</code> and
117 * <code>returnType</code> information are added to the builder.
119 * @param interfaceBuilder
120 * generated type builder for which the getter method should be
122 * @param schemaNodeName
123 * string with schema node name. The name will be the part of the
124 * getter method name.
126 * string with comment for the getter method
128 * type which represents the return type of the getter method
130 * status from yang file, for deprecated annotation
131 * @return method signature builder which represents the getter method of
132 * <code>interfaceBuilder</code>
134 static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
135 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
137 final MethodSignatureBuilder getMethod = interfaceBuilder
138 .addMethod(getterMethodName(schemaNodeName, returnType));
139 if (status == Status.DEPRECATED) {
140 getMethod.addAnnotation("", "Deprecated");
142 getMethod.setComment(encodeAngleBrackets(comment));
143 getMethod.setReturnType(returnType);
148 * Creates the name of the getter method name from <code>localName</code>.
151 * string with the name of the getter method
154 * @return string with the name of the getter method for
155 * <code>methodName</code> in JAVA method format
157 private static String getterMethodName(final String localName, final Type returnType) {
158 final StringBuilder method = new StringBuilder();
159 if (BOOLEAN.equals(returnType)) {
162 method.append("get");
164 // underscore used as separator for distinction of method parts in convertIdentifier()
165 method.append('_').append(localName);
166 return JavaIdentifierNormalizer.normalizeSpecificIdentifier(method.toString(), JavaIdentifier.METHOD);
169 static String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName,
170 final SchemaContext schemaContext, final boolean verboseClassComments,
171 final BindingNamespaceType namespaceType) {
172 final StringBuilder sb = new StringBuilder();
173 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
174 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
176 if (!Strings.isNullOrEmpty(formattedDescription)) {
177 sb.append(formattedDescription);
181 final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
182 if (verboseClassComments) {
184 sb.append("This class represents the following YANG schema fragment defined in module <b>");
185 sb.append(module.getName());
190 String formedYang = YangSnippetCleaner.clean(yangTemplateForNode.render(schemaNode, module).body());
191 sb.append(encodeAngleBrackets(formedYang));
194 sb.append("The schema path to identify an instance is");
197 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
201 if (hasBuilderClass(schemaNode, namespaceType) && !(schemaNode instanceof OperationDefinition)) {
202 final StringBuilder linkToBuilderClass = new StringBuilder();
203 final String basePackageName = BindingMapping.getRootPackageName(module);
206 .append(replacePackageTopNamespace(basePackageName, fullyQualifiedName,
207 namespaceType, BindingNamespaceType.Builder))
210 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
213 sb.append(linkToBuilderClass);
215 if (schemaNode instanceof ListSchemaNode) {
216 final StringBuilder linkToKeyClass = new StringBuilder();
218 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
219 final String className = namespace[namespace.length - 1];
221 linkToKeyClass.append(BindingGeneratorUtil.packageNameForSubGeneratedType(basePackageName, schemaNode,
222 BindingNamespaceType.Key))
227 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
228 if (keyDef != null && !keyDef.isEmpty()) {
230 sb.append(linkToKeyClass);
237 return replaceAllIllegalChars(sb);
240 static String createDescription(final Module module, final boolean verboseClassComments) {
241 final StringBuilder sb = new StringBuilder();
242 final String moduleDescription = encodeAngleBrackets(module.getDescription());
243 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
245 if (!Strings.isNullOrEmpty(formattedDescription)) {
246 sb.append(formattedDescription);
250 if (verboseClassComments) {
252 sb.append("This class represents the following YANG schema fragment defined in module <b>");
253 sb.append(module.getName());
258 String formedYang = YangSnippetCleaner.clean(yangTemplateForModule.render(module).body());
259 sb.append(encodeAngleBrackets(formedYang));
263 return replaceAllIllegalChars(sb);
266 static String createDescription(final Set<? extends SchemaNode> schemaNodes, final Module module, final
267 boolean verboseClassComments) {
268 final StringBuilder sb = new StringBuilder();
270 if (!isNullOrEmpty(schemaNodes)) {
271 final SchemaNode node = schemaNodes.iterator().next();
273 if (node instanceof RpcDefinition) {
274 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + module.getName() + "</b>");
275 } else if (node instanceof NotificationDefinition) {
276 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + module.getName() + "</b>");
281 if (verboseClassComments) {
284 sb.append(encodeAngleBrackets(yangTemplateForNodes.render(schemaNodes, module).body()));
289 return replaceAllIllegalChars(sb);
292 private static boolean isNullOrEmpty(final Collection<?> list) {
293 return list == null || list.isEmpty();
297 * Returns first unique name for the augment generated type builder. The
298 * generated type builder name for augment consists from name of augmented
299 * node and serial number of its augmentation.
302 * map of builders which were created in the package to which the
303 * augmentation belongs
305 * string with name of augmented node
306 * @return string with unique name for augmentation builder
308 static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
310 if (builders != null) {
311 while (builders.containsKey(genTypeName + index)) {
315 return genTypeName + index;
319 * @param unknownSchemaNodes unknown schema nodes
320 * @return nodeParameter of UnknownSchemaNode
322 static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
323 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
324 final QName nodeType = unknownSchemaNode.getNodeType();
325 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
326 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
327 return unknownSchemaNode.getNodeParameter();
334 * Adds enumeration builder created from <code>enumTypeDef</code> to
335 * <code>typeBuilder</code>.
337 * Each <code>enumTypeDef</code> item is added to builder with its name and
341 * EnumTypeDefinition contains enum data
343 * string contains name which will be assigned to enumeration
346 * GeneratedTypeBuilder to which will be enum builder assigned
348 * Module in which type should be generated
349 * @return enumeration builder which contains data from
350 * <code>enumTypeDef</code>
352 static EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
353 final Map<Module, ModuleContext> genCtx, final GeneratedTypeBuilder typeBuilder, final Module module) {
354 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
355 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName.getLocalName());
356 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
357 enumBuilder.setDescription(enumTypedefDescription);
358 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
359 final ModuleContext ctx = genCtx.get(module);
360 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
368 * Builds generated TO builders for <code>typeDef</code> of type
369 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
370 * also added to <code>typeBuilder</code> as enclosing transfer object.
372 * If more then one generated TO builder is created for enclosing then all
373 * of the generated TO builders are added to <code>typeBuilder</code> as
374 * enclosing transfer objects.
377 * type definition which can be of type <code>UnionType</code> or
378 * <code>BitsTypeDefinition</code>
380 * generated type builder to which is added generated TO created
381 * from <code>typeDef</code>
383 * string with name for generated TO builder
384 * @param parentModule
386 * @return generated TO builder for <code>typeDef</code>
388 static GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef, final GeneratedTypeBuilder
389 typeBuilder, final DataSchemaNode leaf, final Module parentModule, final TypeProvider typeProvider,
390 final SchemaContext schemaContext) {
391 final String classNameFromLeaf = leaf.getQName().getLocalName();
392 GeneratedTOBuilder genTOBuilder = null;
393 final String packageName = typeBuilder.getFullyQualifiedName();
394 if (typeDef instanceof UnionTypeDefinition) {
395 genTOBuilder = ((TypeProviderImpl) typeProvider)
396 .provideGeneratedTOBuilderForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
397 classNameFromLeaf, leaf, schemaContext,
398 ((TypeProviderImpl) typeProvider).getGenTypeDefsContextMap());
399 } else if (typeDef instanceof BitsTypeDefinition) {
400 genTOBuilder = (((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
401 packageName, typeDef, classNameFromLeaf, parentModule.getName());
403 if (genTOBuilder != null) {
404 typeBuilder.addEnclosingTransferObject(genTOBuilder);
411 @SuppressWarnings({ "unchecked", "rawtypes" })
412 static Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
413 final GeneratedTypeBuilder typeBuilder, final Module parentModule, final TypeProvider typeProvider) {
414 final GeneratedTOBuilderImpl returnType = (GeneratedTOBuilderImpl) genTOBuilder;
415 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
417 returnType.setDescription(typedefDescription);
418 returnType.setReference(typeDef.getReference());
419 returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
420 returnType.setModuleName(parentModule.getName());
422 genTOBuilder.setTypedef(true);
423 genTOBuilder.setIsUnion(true);
424 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
426 return returnType.toInstance();
429 static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
430 return leaf.getPath().equals(type.getPath()) || leaf.getPath().equals(type.getPath().getParent());
435 * Generates for the <code>list</code> which contains any list keys special
436 * generated TO builder.
439 * string with package name to which the list belongs
441 * schema node of list
442 * @return generated TO builder which represents the keys of the
443 * <code>list</code> or empty TO builder if <code>list</code> is null or list of
444 * key definitions is null or empty.
446 static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
447 GeneratedTOBuilder genTOBuilder = null;
448 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
449 // underscore used as separator for distinction of class name parts
450 final String genTOName =
451 new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key)
453 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
458 static GeneratedTypeBuilder resolveListKeyTypeBuilder(final String packageName, final ListSchemaNode list) {
459 GeneratedTypeBuilder genTypeBuilder = null;
460 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
461 // underscore used as separator for distinction of class name parts
462 final String genTOName =
463 new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key)
465 genTypeBuilder = new GeneratedTypeBuilderImpl(packageName, genTOName);
467 return genTypeBuilder;
471 * Converts <code>leaf</code> schema node to property of generated TO
475 * generated TO builder to which is <code>leaf</code> added as
478 * leaf schema node which is added to <code>toBuilder</code> as
483 * boolean value which says if leaf property is|isn't read only
484 * @return boolean value
486 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
487 * name equals null or if leaf is added by <i>uses</i>.</li>
488 * <li>true - other cases</li>
491 static boolean resolveLeafSchemaNodeAsProperty(final String nodeName, final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
492 final Type returnType, final boolean isReadOnly) {
494 if (returnType == null) {
497 final String leafName = leaf.getQName().getLocalName();
498 final String leafGetterName;
500 StringBuilder sb = new StringBuilder(nodeName)
503 leafGetterName = sb.toString();
505 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
506 final GeneratedPropertyBuilder propBuilder =
507 toBuilder.addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(leafGetterName, JavaIdentifier.METHOD));
508 propBuilder.setReadOnly(isReadOnly);
509 propBuilder.setReturnType(returnType);
510 propBuilder.setComment(leafDesc);
511 toBuilder.addEqualsIdentity(propBuilder);
512 toBuilder.addHashIdentity(propBuilder);
513 toBuilder.addToStringProperty(propBuilder);
517 static void checkModuleAndModuleName(final Module module) {
518 checkArgument(module != null, "Module reference cannot be NULL.");
519 checkArgument(module.getName() != null, "Module name cannot be NULL.");
523 public static String replaceAllIllegalChars(final StringBuilder stringBuilder){
524 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
525 return ret.isEmpty() ? "" : ret;