Binding generator v2 - fix case builder to dto
[mdsal.git] / binding2 / mdsal-binding2-generator-impl / src / main / java / org / opendaylight / mdsal / binding / javav2 / generator / impl / AuxiliaryGenUtils.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.mdsal.binding.javav2.generator.impl;
10
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;
15
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;
23 import java.util.Map;
24 import java.util.Set;
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;
68
69 /**
70  * Auxiliary util class for {@link GenHelperUtil} class
71  */
72 @Beta
73 final class AuxiliaryGenUtils {
74
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");
78
79     /**
80      * Constant with the concrete name of identifier.
81      */
82     private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
83
84     /**
85      * Constant with the concrete name of namespace.
86      */
87     private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
88
89     private AuxiliaryGenUtils() {
90         throw new UnsupportedOperationException("Util class");
91     }
92
93     static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
94         if (status == Status.DEPRECATED) {
95             builder.addAnnotation("", "Deprecated");
96         }
97     }
98
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))) {
104             return true;
105         }
106         return false;
107     }
108
109     static Constant qNameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
110                                   final QName name) {
111         return toBuilder.addConstant(Types.typeForClass(QName.class), constantName, name);
112     }
113
114     /**
115      * Created a method signature builder as part of
116      * <code>interfaceBuilder</code>.
117      *
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.
121      *
122      * @param interfaceBuilder
123      *            generated type builder for which the getter method should be
124      *            created
125      * @param schemaNodeName
126      *            string with schema node name. The name will be the part of the
127      *            getter method name.
128      * @param comment
129      *            string with comment for the getter method
130      * @param returnType
131      *            type which represents the return type of the getter method
132      * @param status
133      *            status from yang file, for deprecated annotation
134      * @return method signature builder which represents the getter method of
135      *         <code>interfaceBuilder</code>
136      */
137     static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
138                                                   final String schemaNodeName, final String comment, final Type returnType, final Status status) {
139
140         final MethodSignatureBuilder getMethod = interfaceBuilder
141                 .addMethod(getterMethodName(schemaNodeName, returnType));
142         if (status == Status.DEPRECATED) {
143             getMethod.addAnnotation("", "Deprecated");
144         }
145         getMethod.setComment(encodeAngleBrackets(comment));
146         getMethod.setReturnType(returnType);
147         return getMethod;
148     }
149
150     /**
151      * Creates the name of the getter method name from <code>localName</code>.
152      *
153      * @param localName
154      *            string with the name of the getter method
155      * @param returnType
156      *            return type
157      * @return string with the name of the getter method for
158      *         <code>methodName</code> in JAVA method format
159      */
160     private static String getterMethodName(final String localName, final Type returnType) {
161         final StringBuilder method = new StringBuilder();
162         if (BOOLEAN.equals(returnType)) {
163             method.append("is");
164         } else {
165             method.append("get");
166         }
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);
170     }
171
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);
178
179         if (!Strings.isNullOrEmpty(formattedDescription)) {
180             sb.append(formattedDescription);
181             sb.append(NEW_LINE);
182         }
183
184         final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
185         if (verboseClassComments) {
186             sb.append("<p>");
187             sb.append("This class represents the following YANG schema fragment defined in module <b>");
188             sb.append(module.getName());
189             sb.append("</b>");
190             sb.append(NEW_LINE);
191             sb.append("<pre>");
192             sb.append(NEW_LINE);
193             String formedYang = YangSnippetCleaner.clean(yangTemplateForNode.render(schemaNode, module).body());
194             sb.append(encodeAngleBrackets(formedYang));
195             sb.append("</pre>");
196             sb.append(NEW_LINE);
197             sb.append("The schema path to identify an instance is");
198             sb.append(NEW_LINE);
199             sb.append("<i>");
200             sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
201             sb.append("</i>");
202             sb.append(NEW_LINE);
203
204             if (hasBuilderClass(schemaNode, namespaceType) && !(schemaNode instanceof OperationDefinition)) {
205                 final StringBuilder linkToBuilderClass = new StringBuilder();
206                 final String basePackageName = BindingMapping.getRootPackageName(module);
207
208                 linkToBuilderClass
209                         .append(replacePackageTopNamespace(basePackageName, fullyQualifiedName,
210                                 namespaceType, BindingNamespaceType.Builder))
211                         .append("Builder");
212                 sb.append(NEW_LINE);
213                 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
214                 sb.append(NEW_LINE);
215                 sb.append("@see ");
216                 sb.append(linkToBuilderClass);
217                 sb.append(NEW_LINE);
218                 if (schemaNode instanceof ListSchemaNode) {
219                     final StringBuilder linkToKeyClass = new StringBuilder();
220
221                     final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
222                     final String className = namespace[namespace.length - 1];
223
224                     linkToKeyClass.append(BindingGeneratorUtil.packageNameForSubGeneratedType(basePackageName, schemaNode,
225                             BindingNamespaceType.Key))
226                             .append('.')
227                             .append(className)
228                             .append("Key");
229
230                     final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
231                     if (keyDef != null && !keyDef.isEmpty()) {
232                         sb.append("@see ");
233                         sb.append(linkToKeyClass).append(className).append("Key");
234                     }
235                     sb.append(NEW_LINE);
236                 }
237             }
238         }
239
240         return replaceAllIllegalChars(sb);
241     }
242
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);
247
248         if (!Strings.isNullOrEmpty(formattedDescription)) {
249             sb.append(formattedDescription);
250             sb.append(NEW_LINE);
251         }
252
253         if (verboseClassComments) {
254             sb.append("<p>");
255             sb.append("This class represents the following YANG schema fragment defined in module <b>");
256             sb.append(module.getName());
257             sb.append("</b>");
258             sb.append(NEW_LINE);
259             sb.append("<pre>");
260             sb.append(NEW_LINE);
261             String formedYang = YangSnippetCleaner.clean(yangTemplateForModule.render(module).body());
262             sb.append(encodeAngleBrackets(formedYang));
263             sb.append("</pre>");
264         }
265
266         return replaceAllIllegalChars(sb);
267     }
268
269     static String createDescription(final Set<? extends SchemaNode> schemaNodes, final Module module, final
270             boolean verboseClassComments) {
271         final StringBuilder sb = new StringBuilder();
272
273         if (!isNullOrEmpty(schemaNodes)) {
274             final SchemaNode node = schemaNodes.iterator().next();
275
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>");
280             }
281         }
282         sb.append(NEW_LINE);
283
284         if (verboseClassComments) {
285             sb.append("<pre>");
286             sb.append(NEW_LINE);
287             sb.append(encodeAngleBrackets(yangTemplateForNodes.render(schemaNodes, module).body()));
288             sb.append("</pre>");
289             sb.append(NEW_LINE);
290         }
291
292         return replaceAllIllegalChars(sb);
293     }
294
295     private static boolean isNullOrEmpty(final Collection<?> list) {
296         return list == null || list.isEmpty();
297     }
298
299     /**
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.
303      *
304      * @param builders
305      *            map of builders which were created in the package to which the
306      *            augmentation belongs
307      * @param genTypeName
308      *            string with name of augmented node
309      * @return string with unique name for augmentation builder
310      */
311     static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
312         int index = 1;
313         if (builders != null) {
314             while (builders.containsKey(genTypeName + index)) {
315                 index = index + 1;
316             }
317         }
318         return genTypeName + index;
319     }
320
321     /**
322      * @param unknownSchemaNodes unknown schema nodes
323      * @return nodeParameter of UnknownSchemaNode
324      */
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();
331             }
332         }
333         return null;
334     }
335
336     /**
337      * Adds enumeration builder created from <code>enumTypeDef</code> to
338      * <code>typeBuilder</code>.
339      *
340      * Each <code>enumTypeDef</code> item is added to builder with its name and
341      * value.
342      *
343      * @param enumTypeDef
344      *            EnumTypeDefinition contains enum data
345      * @param enumName
346      *            string contains name which will be assigned to enumeration
347      *            builder
348      * @param typeBuilder
349      *            GeneratedTypeBuilder to which will be enum builder assigned
350      * @param module
351      *            Module in which type should be generated
352      * @return enumeration builder which contains data from
353      *         <code>enumTypeDef</code>
354      */
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);
364             return enumBuilder;
365         }
366         return null;
367     }
368
369
370     /**
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.
374      *
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.
378      *
379      * @param typeDef
380      *            type definition which can be of type <code>UnionType</code> or
381      *            <code>BitsTypeDefinition</code>
382      * @param typeBuilder
383      *            generated type builder to which is added generated TO created
384      *            from <code>typeDef</code>
385      * @param leaf
386      *            string with name for generated TO builder
387      * @param parentModule
388      *            parent module
389      * @return generated TO builder for <code>typeDef</code>
390      */
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());
405         }
406         if (genTOBuilder != null) {
407             typeBuilder.addEnclosingTransferObject(genTOBuilder);
408             return genTOBuilder;
409         }
410         return null;
411
412     }
413
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());
419
420         returnType.setDescription(typedefDescription);
421         returnType.setReference(typeDef.getReference());
422         returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
423         returnType.setModuleName(parentModule.getName());
424
425         genTOBuilder.setTypedef(true);
426         genTOBuilder.setIsUnion(true);
427         TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
428
429         return returnType.toInstance();
430     }
431
432     static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
433         if (leaf.getPath().equals(type.getPath())) {
434             return true;
435         }
436         if (leaf.getPath().equals(type.getPath().getParent())) {
437             return true;
438         }
439
440         return false;
441     }
442
443     /**
444      * Generates for the <code>list</code> which contains any list keys special
445      * generated TO builder.
446      *
447      * @param packageName
448      *            string with package name to which the list belongs
449      * @param list
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.
454      */
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)
461                             .toString();
462             genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
463         }
464         return genTOBuilder;
465     }
466
467     /**
468      * Converts <code>leaf</code> schema node to property of generated TO
469      * builder.
470      *
471      * @param toBuilder
472      *            generated TO builder to which is <code>leaf</code> added as
473      *            property
474      * @param leaf
475      *            leaf schema node which is added to <code>toBuilder</code> as
476      *            property
477      * @param returnType
478      *            property type
479      * @param isReadOnly
480      *            boolean value which says if leaf property is|isn't read only
481      * @return boolean value
482      *         <ul>
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>
486      *         </ul>
487      */
488     static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
489         final Type returnType, final boolean isReadOnly) {
490
491         if (returnType == null) {
492             return false;
493         }
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);
504         return true;
505     }
506
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.");
510     }
511
512     @VisibleForTesting
513     public static String replaceAllIllegalChars(final StringBuilder stringBuilder){
514         final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
515         return ret.isEmpty() ? "" : ret;
516     }
517 }