Bug 1411 #4 BindingGeneratorImpl decomposition - Lists
[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 org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
12 import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.BOOLEAN;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Splitter;
17 import com.google.common.base.Strings;
18 import com.google.common.collect.Iterables;
19 import com.google.common.collect.Sets;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.regex.Pattern;
25 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForModule;
26 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForNode;
27 import org.opendaylight.mdsal.binding.javav2.generator.impl.util.YangTextTemplate;
28 import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
29 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier;
30 import org.opendaylight.mdsal.binding.javav2.generator.util.NonJavaCharsConverter;
31 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
32 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
33 import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl;
34 import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier;
35 import org.opendaylight.mdsal.binding.javav2.model.api.Constant;
36 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
37 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder;
38 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder;
39 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
40 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder;
41 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase;
42 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder;
43 import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.Module;
50 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
51 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
52 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.Status;
55 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
61
62 /**
63  * Auxiliary util class for {@link GenHelperUtil} class
64  */
65 @Beta
66 final class AuxiliaryGenUtils {
67
68     private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
69     private static final char NEW_LINE = '\n';
70     private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
71
72     /**
73      * Constant with the concrete name of identifier.
74      */
75     private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
76
77     /**
78      * Constant with the concrete name of namespace.
79      */
80     private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
81
82     private AuxiliaryGenUtils() {
83         throw new UnsupportedOperationException("Util class");
84     }
85
86     static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
87         if (status == Status.DEPRECATED) {
88             builder.addAnnotation("", "Deprecated");
89         }
90     }
91
92     private static boolean hasBuilderClass(final SchemaNode schemaNode) {
93         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
94                 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
95             return true;
96         }
97         return false;
98     }
99
100     static Constant qNameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
101                                   final QName name) {
102         return toBuilder.addConstant(Types.typeForClass(QName.class), constantName, name);
103     }
104
105     /**
106      * Created a method signature builder as part of
107      * <code>interfaceBuilder</code>.
108      *
109      * The method signature builder is created for the getter method of
110      * <code>schemaNodeName</code>. Also <code>comment</code> and
111      * <code>returnType</code> information are added to the builder.
112      *
113      * @param interfaceBuilder
114      *            generated type builder for which the getter method should be
115      *            created
116      * @param schemaNodeName
117      *            string with schema node name. The name will be the part of the
118      *            getter method name.
119      * @param comment
120      *            string with comment for the getter method
121      * @param returnType
122      *            type which represents the return type of the getter method
123      * @param status
124      *            status from yang file, for deprecated annotation
125      * @return method signature builder which represents the getter method of
126      *         <code>interfaceBuilder</code>
127      */
128     static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
129                                                   final String schemaNodeName, final String comment, final Type returnType, final Status status) {
130
131         final MethodSignatureBuilder getMethod = interfaceBuilder
132                 .addMethod(getterMethodName(schemaNodeName, returnType));
133         if (status == Status.DEPRECATED) {
134             getMethod.addAnnotation("", "Deprecated");
135         }
136         getMethod.setComment(encodeAngleBrackets(comment));
137         getMethod.setReturnType(returnType);
138         return getMethod;
139     }
140
141     /**
142      * Creates the name of the getter method name from <code>localName</code>.
143      *
144      * @param localName
145      *            string with the name of the getter method
146      * @param returnType
147      *            return type
148      * @return string with the name of the getter method for
149      *         <code>methodName</code> in JAVA method format
150      */
151     private static String getterMethodName(final String localName, final Type returnType) {
152         final StringBuilder method = new StringBuilder();
153         if (BOOLEAN.equals(returnType)) {
154             method.append("is");
155         } else {
156             method.append("get");
157         }
158         // underscore used as separator for distinction of method parts in convertIdentifier()
159         method.append('_').append(localName);
160         return NonJavaCharsConverter.convertIdentifier(method.toString(), JavaIdentifier.METHOD);
161     }
162
163     static String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName,
164                                     final SchemaContext schemaContext, final boolean verboseClassComments) {
165         final StringBuilder sb = new StringBuilder();
166         final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
167         final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
168
169         if (!Strings.isNullOrEmpty(formattedDescription)) {
170             sb.append(formattedDescription);
171             sb.append(NEW_LINE);
172         }
173
174         if (verboseClassComments) {
175             final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
176             final StringBuilder linkToBuilderClass = new StringBuilder();
177             final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
178             final String className = namespace[namespace.length - 1];
179
180             if (hasBuilderClass(schemaNode)) {
181                 linkToBuilderClass.append(className);
182                 linkToBuilderClass.append("Builder");
183             }
184
185             sb.append("<p>");
186             sb.append("This class represents the following YANG schema fragment defined in module <b>");
187             sb.append(module.getName());
188             sb.append("</b>");
189             sb.append(NEW_LINE);
190             sb.append("<pre>");
191             sb.append(NEW_LINE);
192             sb.append(encodeAngleBrackets(yangTemplateForNode.render(schemaNode).body()));
193             sb.append("</pre>");
194             sb.append(NEW_LINE);
195             sb.append("The schema path to identify an instance is");
196             sb.append(NEW_LINE);
197             sb.append("<i>");
198             sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
199             sb.append("</i>");
200             sb.append(NEW_LINE);
201
202             if (hasBuilderClass(schemaNode)) {
203                 sb.append(NEW_LINE);
204                 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
205                 sb.append(NEW_LINE);
206                 sb.append("@see ");
207                 sb.append(linkToBuilderClass);
208                 sb.append(NEW_LINE);
209                 if (schemaNode instanceof ListSchemaNode) {
210                     final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
211                     if (keyDef != null && !keyDef.isEmpty()) {
212                         sb.append("@see ");
213                         sb.append(className);
214                         sb.append("Key");
215                     }
216                     sb.append(NEW_LINE);
217                 }
218             }
219         }
220
221         return replaceAllIllegalChars(sb);
222     }
223
224     static String createDescription(final Module module, final boolean verboseClassComments) {
225         final StringBuilder sb = new StringBuilder();
226         final String moduleDescription = encodeAngleBrackets(module.getDescription());
227         final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
228
229         if (!Strings.isNullOrEmpty(formattedDescription)) {
230             sb.append(formattedDescription);
231             sb.append(NEW_LINE);
232         }
233
234         if (verboseClassComments) {
235             sb.append("<p>");
236             sb.append("This class represents the following YANG schema fragment defined in module <b>");
237             sb.append(module.getName());
238             sb.append("</b>");
239             sb.append(NEW_LINE);
240             sb.append("<pre>");
241             sb.append(NEW_LINE);
242             sb.append(encodeAngleBrackets(yangTemplateForModule.render(module).body()));
243             sb.append("</pre>");
244         }
245
246         return replaceAllIllegalChars(sb);
247     }
248
249     /**
250      * Returns first unique name for the augment generated type builder. The
251      * generated type builder name for augment consists from name of augmented
252      * node and serial number of its augmentation.
253      *
254      * @param builders
255      *            map of builders which were created in the package to which the
256      *            augmentation belongs
257      * @param genTypeName
258      *            string with name of augmented node
259      * @return string with unique name for augmentation builder
260      */
261     static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
262         int index = 1;
263         if (builders != null) {
264             while (builders.containsKey(genTypeName + index)) {
265                 index = index + 1;
266             }
267         }
268         return genTypeName + index;
269     }
270
271     /**
272      * @param unknownSchemaNodes unknows schema nodes
273      * @return nodeParameter of UnknownSchemaNode
274      */
275     static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
276         for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
277             final QName nodeType = unknownSchemaNode.getNodeType();
278             if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
279                     && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
280                 return unknownSchemaNode.getNodeParameter();
281             }
282         }
283         return null;
284     }
285
286     /**
287      * Adds enumeration builder created from <code>enumTypeDef</code> to
288      * <code>typeBuilder</code>.
289      *
290      * Each <code>enumTypeDef</code> item is added to builder with its name and
291      * value.
292      *
293      * @param enumTypeDef
294      *            EnumTypeDefinition contains enum data
295      * @param enumName
296      *            string contains name which will be assigned to enumeration
297      *            builder
298      * @param typeBuilder
299      *            GeneratedTypeBuilder to which will be enum builder assigned
300      * @param module
301      *            Module in which type should be generated
302      * @return enumeration builder which contains data from
303      *         <code>enumTypeDef</code>
304      */
305     static EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
306         final Map<Module, ModuleContext> genCtx, final GeneratedTypeBuilder typeBuilder, final Module module) {
307         if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
308             final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName.getLocalName());
309             final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
310             enumBuilder.setDescription(enumTypedefDescription);
311             enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
312             final ModuleContext ctx = genCtx.get(module);
313             ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
314             return enumBuilder;
315         }
316         return null;
317     }
318
319
320     /**
321      * Builds generated TO builders for <code>typeDef</code> of type
322      * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
323      * also added to <code>typeBuilder</code> as enclosing transfer object.
324      *
325      * If more then one generated TO builder is created for enclosing then all
326      * of the generated TO builders are added to <code>typeBuilder</code> as
327      * enclosing transfer objects.
328      *
329      * @param typeDef
330      *            type definition which can be of type <code>UnionType</code> or
331      *            <code>BitsTypeDefinition</code>
332      * @param typeBuilder
333      *            generated type builder to which is added generated TO created
334      *            from <code>typeDef</code>
335      * @param leaf
336      *            string with name for generated TO builder
337      * @param parentModule
338      *            parent module
339      * @return generated TO builder for <code>typeDef</code>
340      */
341     static GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef, final GeneratedTypeBuilder
342             typeBuilder, final DataSchemaNode leaf, final Module parentModule, final TypeProvider typeProvider,
343             final SchemaContext schemaContext) {
344         final String classNameFromLeaf = leaf.getQName().getLocalName();
345         final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
346         final String packageName = typeBuilder.getFullyQualifiedName();
347         if (typeDef instanceof UnionTypeDefinition) {
348             final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
349                     .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
350                             classNameFromLeaf, leaf, schemaContext, ((TypeProviderImpl) typeProvider).getGenTypeDefsContextMap());
351             genTOBuilders.addAll(types);
352
353             GeneratedTOBuilder resultTOBuilder;
354             if (types.isEmpty()) {
355                 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
356             }
357             resultTOBuilder = types.remove(0);
358             for (final GeneratedTOBuilder genTOBuilder : types) {
359                 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
360             }
361
362             final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
363             genPropBuilder.setReturnType(Types.CHAR_ARRAY);
364             resultTOBuilder.addEqualsIdentity(genPropBuilder);
365             resultTOBuilder.addHashIdentity(genPropBuilder);
366             resultTOBuilder.addToStringProperty(genPropBuilder);
367
368         } else if (typeDef instanceof BitsTypeDefinition) {
369             genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
370                     packageName, typeDef, classNameFromLeaf, parentModule.getName()));
371         }
372         if (!genTOBuilders.isEmpty()) {
373             for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
374                 typeBuilder.addEnclosingTransferObject(genTOBuilder);
375             }
376             return genTOBuilders.get(0);
377         }
378         return null;
379
380     }
381
382     @SuppressWarnings({ "unchecked", "rawtypes" })
383     static Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
384             final GeneratedTypeBuilder typeBuilder, final Module parentModule, final TypeProvider typeProvider) {
385         final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
386                 genTOBuilder.getName());
387         final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
388
389         returnType.setDescription(typedefDescription);
390         returnType.setReference(typeDef.getReference());
391         returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
392         returnType.setModuleName(parentModule.getName());
393
394         genTOBuilder.setTypedef(true);
395         genTOBuilder.setIsUnion(true);
396         TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
397
398
399
400         final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
401
402
403         final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
404         method.setReturnType(returnType);
405         method.addParameter(Types.STRING, "defaultValue");
406         method.setAccessModifier(AccessModifier.PUBLIC);
407         method.setStatic(true);
408
409         final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
410         if (types == null) {
411             ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
412                     Sets.newHashSet(unionBuilder.toInstance()));
413         } else {
414             types.add(unionBuilder.toInstance());
415         }
416         return returnType.toInstance();
417     }
418
419     private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
420         final String outerCls = Types.getOuterClassName(genTOBuilder);
421         final StringBuilder name;
422         if (outerCls != null) {
423             name = new StringBuilder(outerCls);
424         } else {
425             name = new StringBuilder();
426         }
427         name.append(genTOBuilder.getName());
428         name.append("Builder");
429         final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
430         unionBuilder.setIsUnionBuilder(true);
431         return unionBuilder;
432     }
433
434     static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
435         if (leaf.getPath().equals(type.getPath())) {
436             return true;
437         }
438         if (leaf.getPath().equals(type.getPath().getParent())) {
439             return true;
440         }
441
442         return false;
443     }
444
445     /**
446      * Generates for the <code>list</code> which contains any list keys special
447      * generated TO builder.
448      *
449      * @param packageName
450      *            string with package name to which the list belongs
451      * @param list
452      *            schema node of list
453      * @return generated TO builder which represents the keys of the
454      *         <code>list</code> or empty TO builder if <code>list</code> is null or list of
455      *         key definitions is null or empty.
456      */
457     static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
458         GeneratedTOBuilder genTOBuilder = null;
459         if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
460             // underscore used as separator for distinction of class name parts
461             final String genTOName =
462                     new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key)
463                             .toString();
464             genTOBuilder =
465                     new GeneratedTOBuilderImpl(new StringBuilder(packageName).append(".wrapper").toString(), genTOName);
466         }
467         return genTOBuilder;
468     }
469
470     /**
471      * Converts <code>leaf</code> schema node to property of generated TO
472      * builder.
473      *
474      * @param toBuilder
475      *            generated TO builder to which is <code>leaf</code> added as
476      *            property
477      * @param leaf
478      *            leaf schema node which is added to <code>toBuilder</code> as
479      *            property
480      * @param returnType
481      *            property type
482      * @param isReadOnly
483      *            boolean value which says if leaf property is|isn't read only
484      * @return boolean value
485      *         <ul>
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>
489      *         </ul>
490      */
491     static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
492         final Type returnType, final boolean isReadOnly) {
493
494         if (returnType == null) {
495             return false;
496         }
497         final String leafName = leaf.getQName().getLocalName();
498         final String leafDesc = encodeAngleBrackets(leaf.getDescription());
499         final GeneratedPropertyBuilder propBuilder =
500                 toBuilder.addProperty(NonJavaCharsConverter.convertIdentifier(leafName, JavaIdentifier.METHOD));
501         propBuilder.setReadOnly(isReadOnly);
502         propBuilder.setReturnType(returnType);
503         propBuilder.setComment(leafDesc);
504         toBuilder.addEqualsIdentity(propBuilder);
505         toBuilder.addHashIdentity(propBuilder);
506         toBuilder.addToStringProperty(propBuilder);
507         return true;
508     }
509
510     @VisibleForTesting
511     public static String replaceAllIllegalChars(final StringBuilder stringBuilder){
512         final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
513         return ret.isEmpty() ? "" : ret;
514     }
515 }