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.api.BindingGenerator;
27 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForModule;
28 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForNode;
29 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForNodes;
30 import org.opendaylight.mdsal.binding.javav2.generator.impl.util.YangTextTemplate;
31 import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
32 import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil;
33 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier;
34 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer;
35 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
36 import org.opendaylight.mdsal.binding.javav2.generator.util.YangSnippetCleaner;
37 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
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 if ((namespaceType.equals(BindingNamespaceType.Data)
101 && (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
102 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition
103 || schemaNode instanceof ChoiceCaseNode))) {
109 static Constant qNameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
111 return toBuilder.addConstant(Types.typeForClass(QName.class), constantName, name);
115 * Created a method signature builder as part of
116 * <code>interfaceBuilder</code>.
118 * The method signature builder is created for the getter method of
119 * <code>schemaNodeName</code>. Also <code>comment</code> and
120 * <code>returnType</code> information are added to the builder.
122 * @param interfaceBuilder
123 * generated type builder for which the getter method should be
125 * @param schemaNodeName
126 * string with schema node name. The name will be the part of the
127 * getter method name.
129 * string with comment for the getter method
131 * type which represents the return type of the getter method
133 * status from yang file, for deprecated annotation
134 * @return method signature builder which represents the getter method of
135 * <code>interfaceBuilder</code>
137 static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
138 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
140 final MethodSignatureBuilder getMethod = interfaceBuilder
141 .addMethod(getterMethodName(schemaNodeName, returnType));
142 if (status == Status.DEPRECATED) {
143 getMethod.addAnnotation("", "Deprecated");
145 getMethod.setComment(encodeAngleBrackets(comment));
146 getMethod.setReturnType(returnType);
151 * Creates the name of the getter method name from <code>localName</code>.
154 * string with the name of the getter method
157 * @return string with the name of the getter method for
158 * <code>methodName</code> in JAVA method format
160 private static String getterMethodName(final String localName, final Type returnType) {
161 final StringBuilder method = new StringBuilder();
162 if (BOOLEAN.equals(returnType)) {
165 method.append("get");
167 // underscore used as separator for distinction of method parts in convertIdentifier()
168 method.append('_').append(localName);
169 return JavaIdentifierNormalizer.normalizeSpecificIdentifier(method.toString(), JavaIdentifier.METHOD);
172 static String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName,
173 final SchemaContext schemaContext, final boolean verboseClassComments,
174 final BindingNamespaceType namespaceType) {
175 final StringBuilder sb = new StringBuilder();
176 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
177 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
179 if (!Strings.isNullOrEmpty(formattedDescription)) {
180 sb.append(formattedDescription);
184 final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
185 if (verboseClassComments) {
187 sb.append("This class represents the following YANG schema fragment defined in module <b>");
188 sb.append(module.getName());
193 String formedYang = YangSnippetCleaner.clean(yangTemplateForNode.render(schemaNode, module).body());
194 sb.append(encodeAngleBrackets(formedYang));
197 sb.append("The schema path to identify an instance is");
200 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
204 if (hasBuilderClass(schemaNode, namespaceType) && !(schemaNode instanceof OperationDefinition)) {
205 final StringBuilder linkToBuilderClass = new StringBuilder();
206 final String basePackageName = BindingMapping.getRootPackageName(module);
209 .append(replacePackageTopNamespace(basePackageName, fullyQualifiedName,
210 namespaceType, BindingNamespaceType.Builder))
213 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
216 sb.append(linkToBuilderClass);
218 if (schemaNode instanceof ListSchemaNode) {
219 final StringBuilder linkToKeyClass = new StringBuilder();
221 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
222 final String className = namespace[namespace.length - 1];
224 linkToKeyClass.append(BindingGeneratorUtil.packageNameForSubGeneratedType(basePackageName, schemaNode,
225 BindingNamespaceType.Key))
230 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
231 if (keyDef != null && !keyDef.isEmpty()) {
233 sb.append(linkToKeyClass).append(className).append("Key");
240 return replaceAllIllegalChars(sb);
243 static String createDescription(final Module module, final boolean verboseClassComments) {
244 final StringBuilder sb = new StringBuilder();
245 final String moduleDescription = encodeAngleBrackets(module.getDescription());
246 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
248 if (!Strings.isNullOrEmpty(formattedDescription)) {
249 sb.append(formattedDescription);
253 if (verboseClassComments) {
255 sb.append("This class represents the following YANG schema fragment defined in module <b>");
256 sb.append(module.getName());
261 String formedYang = YangSnippetCleaner.clean(yangTemplateForModule.render(module).body());
262 sb.append(encodeAngleBrackets(formedYang));
266 return replaceAllIllegalChars(sb);
269 static String createDescription(final Set<? extends SchemaNode> schemaNodes, final Module module, final
270 boolean verboseClassComments) {
271 final StringBuilder sb = new StringBuilder();
273 if (!isNullOrEmpty(schemaNodes)) {
274 final SchemaNode node = schemaNodes.iterator().next();
276 if (node instanceof RpcDefinition) {
277 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + module.getName() + "</b>");
278 } else if (node instanceof NotificationDefinition) {
279 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + module.getName() + "</b>");
284 if (verboseClassComments) {
287 sb.append(encodeAngleBrackets(yangTemplateForNodes.render(schemaNodes, module).body()));
292 return replaceAllIllegalChars(sb);
295 private static boolean isNullOrEmpty(final Collection<?> list) {
296 return list == null || list.isEmpty();
300 * Returns first unique name for the augment generated type builder. The
301 * generated type builder name for augment consists from name of augmented
302 * node and serial number of its augmentation.
305 * map of builders which were created in the package to which the
306 * augmentation belongs
308 * string with name of augmented node
309 * @return string with unique name for augmentation builder
311 static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
313 if (builders != null) {
314 while (builders.containsKey(genTypeName + index)) {
318 return genTypeName + index;
322 * @param unknownSchemaNodes unknown schema nodes
323 * @return nodeParameter of UnknownSchemaNode
325 static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
326 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
327 final QName nodeType = unknownSchemaNode.getNodeType();
328 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
329 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
330 return unknownSchemaNode.getNodeParameter();
337 * Adds enumeration builder created from <code>enumTypeDef</code> to
338 * <code>typeBuilder</code>.
340 * Each <code>enumTypeDef</code> item is added to builder with its name and
344 * EnumTypeDefinition contains enum data
346 * string contains name which will be assigned to enumeration
349 * GeneratedTypeBuilder to which will be enum builder assigned
351 * Module in which type should be generated
352 * @return enumeration builder which contains data from
353 * <code>enumTypeDef</code>
355 static EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
356 final Map<Module, ModuleContext> genCtx, final GeneratedTypeBuilder typeBuilder, final Module module) {
357 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
358 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName.getLocalName());
359 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
360 enumBuilder.setDescription(enumTypedefDescription);
361 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
362 final ModuleContext ctx = genCtx.get(module);
363 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
371 * Builds generated TO builders for <code>typeDef</code> of type
372 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
373 * also added to <code>typeBuilder</code> as enclosing transfer object.
375 * If more then one generated TO builder is created for enclosing then all
376 * of the generated TO builders are added to <code>typeBuilder</code> as
377 * enclosing transfer objects.
380 * type definition which can be of type <code>UnionType</code> or
381 * <code>BitsTypeDefinition</code>
383 * generated type builder to which is added generated TO created
384 * from <code>typeDef</code>
386 * string with name for generated TO builder
387 * @param parentModule
389 * @return generated TO builder for <code>typeDef</code>
391 static GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef, final GeneratedTypeBuilder
392 typeBuilder, final DataSchemaNode leaf, final Module parentModule, final TypeProvider typeProvider,
393 final SchemaContext schemaContext) {
394 final String classNameFromLeaf = leaf.getQName().getLocalName();
395 GeneratedTOBuilder genTOBuilder = null;
396 final String packageName = typeBuilder.getFullyQualifiedName();
397 if (typeDef instanceof UnionTypeDefinition) {
398 genTOBuilder = ((TypeProviderImpl) typeProvider)
399 .provideGeneratedTOBuilderForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
400 classNameFromLeaf, leaf, schemaContext,
401 ((TypeProviderImpl) typeProvider).getGenTypeDefsContextMap());
402 } else if (typeDef instanceof BitsTypeDefinition) {
403 genTOBuilder = (((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
404 packageName, typeDef, classNameFromLeaf, parentModule.getName());
406 if (genTOBuilder != null) {
407 typeBuilder.addEnclosingTransferObject(genTOBuilder);
414 @SuppressWarnings({ "unchecked", "rawtypes" })
415 static Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
416 final GeneratedTypeBuilder typeBuilder, final Module parentModule, final TypeProvider typeProvider) {
417 final GeneratedTOBuilderImpl returnType = (GeneratedTOBuilderImpl) genTOBuilder;
418 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
420 returnType.setDescription(typedefDescription);
421 returnType.setReference(typeDef.getReference());
422 returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
423 returnType.setModuleName(parentModule.getName());
425 genTOBuilder.setTypedef(true);
426 genTOBuilder.setIsUnion(true);
427 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
429 return returnType.toInstance();
432 static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
433 if (leaf.getPath().equals(type.getPath())) {
436 if (leaf.getPath().equals(type.getPath().getParent())) {
444 * Generates for the <code>list</code> which contains any list keys special
445 * generated TO builder.
448 * string with package name to which the list belongs
450 * schema node of list
451 * @return generated TO builder which represents the keys of the
452 * <code>list</code> or empty TO builder if <code>list</code> is null or list of
453 * key definitions is null or empty.
455 static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
456 GeneratedTOBuilder genTOBuilder = null;
457 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
458 // underscore used as separator for distinction of class name parts
459 final String genTOName =
460 new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key)
462 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
468 * Converts <code>leaf</code> schema node to property of generated TO
472 * generated TO builder to which is <code>leaf</code> added as
475 * leaf schema node which is added to <code>toBuilder</code> as
480 * boolean value which says if leaf property is|isn't read only
481 * @return boolean value
483 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
484 * name equals null or if leaf is added by <i>uses</i>.</li>
485 * <li>true - other cases</li>
488 static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
489 final Type returnType, final boolean isReadOnly) {
491 if (returnType == null) {
494 final String leafName = leaf.getQName().getLocalName();
495 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
496 final GeneratedPropertyBuilder propBuilder =
497 toBuilder.addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(leafName, JavaIdentifier.METHOD));
498 propBuilder.setReadOnly(isReadOnly);
499 propBuilder.setReturnType(returnType);
500 propBuilder.setComment(leafDesc);
501 toBuilder.addEqualsIdentity(propBuilder);
502 toBuilder.addHashIdentity(propBuilder);
503 toBuilder.addToStringProperty(propBuilder);
507 static void checkModuleAndModuleName(final Module module) {
508 checkArgument(module != null, "Module reference cannot be NULL.");
509 checkArgument(module.getName() != null, "Module name cannot be NULL.");
513 public static String replaceAllIllegalChars(final StringBuilder stringBuilder){
514 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
515 return ret.isEmpty() ? "" : ret;