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 org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
12 import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.BOOLEAN;
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.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.JavaIdentifier;
32 import org.opendaylight.mdsal.binding.javav2.generator.util.NonJavaCharsConverter;
33 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
34 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
35 import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl;
36 import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier;
37 import org.opendaylight.mdsal.binding.javav2.model.api.Constant;
38 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
39 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder;
40 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder;
41 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
42 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder;
43 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase;
44 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder;
45 import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.Module;
52 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
53 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.Status;
57 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
65 * Auxiliary util class for {@link GenHelperUtil} class
68 final class AuxiliaryGenUtils {
70 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
71 private static final char NEW_LINE = '\n';
72 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
75 * Constant with the concrete name of identifier.
77 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
80 * Constant with the concrete name of namespace.
82 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
84 private AuxiliaryGenUtils() {
85 throw new UnsupportedOperationException("Util class");
88 static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
89 if (status == Status.DEPRECATED) {
90 builder.addAnnotation("", "Deprecated");
94 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
95 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
96 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
102 static Constant qNameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
104 return toBuilder.addConstant(Types.typeForClass(QName.class), constantName, name);
108 * Created a method signature builder as part of
109 * <code>interfaceBuilder</code>.
111 * The method signature builder is created for the getter method of
112 * <code>schemaNodeName</code>. Also <code>comment</code> and
113 * <code>returnType</code> information are added to the builder.
115 * @param interfaceBuilder
116 * generated type builder for which the getter method should be
118 * @param schemaNodeName
119 * string with schema node name. The name will be the part of the
120 * getter method name.
122 * string with comment for the getter method
124 * type which represents the return type of the getter method
126 * status from yang file, for deprecated annotation
127 * @return method signature builder which represents the getter method of
128 * <code>interfaceBuilder</code>
130 static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
131 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
133 final MethodSignatureBuilder getMethod = interfaceBuilder
134 .addMethod(getterMethodName(schemaNodeName, returnType));
135 if (status == Status.DEPRECATED) {
136 getMethod.addAnnotation("", "Deprecated");
138 getMethod.setComment(encodeAngleBrackets(comment));
139 getMethod.setReturnType(returnType);
144 * Creates the name of the getter method name from <code>localName</code>.
147 * string with the name of the getter method
150 * @return string with the name of the getter method for
151 * <code>methodName</code> in JAVA method format
153 private static String getterMethodName(final String localName, final Type returnType) {
154 final StringBuilder method = new StringBuilder();
155 if (BOOLEAN.equals(returnType)) {
158 method.append("get");
160 // underscore used as separator for distinction of method parts in convertIdentifier()
161 method.append('_').append(localName);
162 return NonJavaCharsConverter.convertIdentifier(method.toString(), JavaIdentifier.METHOD);
165 static String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName,
166 final SchemaContext schemaContext, final boolean verboseClassComments) {
167 final StringBuilder sb = new StringBuilder();
168 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
169 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
171 if (!Strings.isNullOrEmpty(formattedDescription)) {
172 sb.append(formattedDescription);
176 if (verboseClassComments) {
177 final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
178 final StringBuilder linkToBuilderClass = new StringBuilder();
179 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
180 final String className = namespace[namespace.length - 1];
182 if (hasBuilderClass(schemaNode)) {
183 linkToBuilderClass.append(className);
184 linkToBuilderClass.append("Builder");
188 sb.append("This class represents the following YANG schema fragment defined in module <b>");
189 sb.append(module.getName());
194 sb.append(encodeAngleBrackets(yangTemplateForNode.render(schemaNode).body()));
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)) {
206 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
209 sb.append(linkToBuilderClass);
211 if (schemaNode instanceof ListSchemaNode) {
212 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
213 if (keyDef != null && !keyDef.isEmpty()) {
215 sb.append(className);
223 return replaceAllIllegalChars(sb);
226 static String createDescription(final Module module, final boolean verboseClassComments) {
227 final StringBuilder sb = new StringBuilder();
228 final String moduleDescription = encodeAngleBrackets(module.getDescription());
229 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
231 if (!Strings.isNullOrEmpty(formattedDescription)) {
232 sb.append(formattedDescription);
236 if (verboseClassComments) {
238 sb.append("This class represents the following YANG schema fragment defined in module <b>");
239 sb.append(module.getName());
244 sb.append(encodeAngleBrackets(yangTemplateForModule.render(module).body()));
248 return replaceAllIllegalChars(sb);
251 static String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final
252 boolean verboseClassComments) {
253 final StringBuilder sb = new StringBuilder();
255 if (!isNullOrEmpty(schemaNodes)) {
256 final SchemaNode node = schemaNodes.iterator().next();
258 if (node instanceof RpcDefinition) {
259 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
260 } else if (node instanceof NotificationDefinition) {
261 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
266 if (verboseClassComments) {
269 sb.append(encodeAngleBrackets(yangTemplateForNodes.render(schemaNodes).body()));
274 return replaceAllIllegalChars(sb);
277 private static boolean isNullOrEmpty(final Collection<?> list) {
278 return list == null || list.isEmpty();
282 * Returns first unique name for the augment generated type builder. The
283 * generated type builder name for augment consists from name of augmented
284 * node and serial number of its augmentation.
287 * map of builders which were created in the package to which the
288 * augmentation belongs
290 * string with name of augmented node
291 * @return string with unique name for augmentation builder
293 static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
295 if (builders != null) {
296 while (builders.containsKey(genTypeName + index)) {
300 return genTypeName + index;
304 * @param unknownSchemaNodes unknows schema nodes
305 * @return nodeParameter of UnknownSchemaNode
307 static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
308 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
309 final QName nodeType = unknownSchemaNode.getNodeType();
310 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
311 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
312 return unknownSchemaNode.getNodeParameter();
319 * Adds enumeration builder created from <code>enumTypeDef</code> to
320 * <code>typeBuilder</code>.
322 * Each <code>enumTypeDef</code> item is added to builder with its name and
326 * EnumTypeDefinition contains enum data
328 * string contains name which will be assigned to enumeration
331 * GeneratedTypeBuilder to which will be enum builder assigned
333 * Module in which type should be generated
334 * @return enumeration builder which contains data from
335 * <code>enumTypeDef</code>
337 static EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
338 final Map<Module, ModuleContext> genCtx, final GeneratedTypeBuilder typeBuilder, final Module module) {
339 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
340 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName.getLocalName());
341 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
342 enumBuilder.setDescription(enumTypedefDescription);
343 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
344 final ModuleContext ctx = genCtx.get(module);
345 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
353 * Builds generated TO builders for <code>typeDef</code> of type
354 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
355 * also added to <code>typeBuilder</code> as enclosing transfer object.
357 * If more then one generated TO builder is created for enclosing then all
358 * of the generated TO builders are added to <code>typeBuilder</code> as
359 * enclosing transfer objects.
362 * type definition which can be of type <code>UnionType</code> or
363 * <code>BitsTypeDefinition</code>
365 * generated type builder to which is added generated TO created
366 * from <code>typeDef</code>
368 * string with name for generated TO builder
369 * @param parentModule
371 * @return generated TO builder for <code>typeDef</code>
373 static GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef, final GeneratedTypeBuilder
374 typeBuilder, final DataSchemaNode leaf, final Module parentModule, final TypeProvider typeProvider,
375 final SchemaContext schemaContext) {
376 final String classNameFromLeaf = leaf.getQName().getLocalName();
377 final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
378 final String packageName = typeBuilder.getFullyQualifiedName();
379 if (typeDef instanceof UnionTypeDefinition) {
380 final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
381 .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
382 classNameFromLeaf, leaf, schemaContext, ((TypeProviderImpl) typeProvider).getGenTypeDefsContextMap());
383 genTOBuilders.addAll(types);
385 GeneratedTOBuilder resultTOBuilder;
386 if (types.isEmpty()) {
387 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
389 resultTOBuilder = types.remove(0);
390 for (final GeneratedTOBuilder genTOBuilder : types) {
391 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
394 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
395 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
396 resultTOBuilder.addEqualsIdentity(genPropBuilder);
397 resultTOBuilder.addHashIdentity(genPropBuilder);
398 resultTOBuilder.addToStringProperty(genPropBuilder);
400 } else if (typeDef instanceof BitsTypeDefinition) {
401 genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
402 packageName, typeDef, classNameFromLeaf, parentModule.getName()));
404 if (!genTOBuilders.isEmpty()) {
405 for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
406 typeBuilder.addEnclosingTransferObject(genTOBuilder);
408 return genTOBuilders.get(0);
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 = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
418 genTOBuilder.getName());
419 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
421 returnType.setDescription(typedefDescription);
422 returnType.setReference(typeDef.getReference());
423 returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
424 returnType.setModuleName(parentModule.getName());
426 genTOBuilder.setTypedef(true);
427 genTOBuilder.setIsUnion(true);
428 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
432 final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
435 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
436 method.setReturnType(returnType);
437 method.addParameter(Types.STRING, "defaultValue");
438 method.setAccessModifier(AccessModifier.PUBLIC);
439 method.setStatic(true);
441 final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
443 ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
444 Sets.newHashSet(unionBuilder.toInstance()));
446 types.add(unionBuilder.toInstance());
448 return returnType.toInstance();
451 private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
452 final String outerCls = Types.getOuterClassName(genTOBuilder);
453 final StringBuilder name;
454 if (outerCls != null) {
455 name = new StringBuilder(outerCls);
457 name = new StringBuilder();
459 name.append(genTOBuilder.getName());
460 name.append("Builder");
461 final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
462 unionBuilder.setIsUnionBuilder(true);
466 static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
467 if (leaf.getPath().equals(type.getPath())) {
470 if (leaf.getPath().equals(type.getPath().getParent())) {
478 * Generates for the <code>list</code> which contains any list keys special
479 * generated TO builder.
482 * string with package name to which the list belongs
484 * schema node of list
485 * @return generated TO builder which represents the keys of the
486 * <code>list</code> or empty TO builder if <code>list</code> is null or list of
487 * key definitions is null or empty.
489 static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
490 GeneratedTOBuilder genTOBuilder = null;
491 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
492 // underscore used as separator for distinction of class name parts
493 final String genTOName =
494 new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key)
497 new GeneratedTOBuilderImpl(new StringBuilder(packageName).append(".wrapper").toString(), genTOName);
503 * Converts <code>leaf</code> schema node to property of generated TO
507 * generated TO builder to which is <code>leaf</code> added as
510 * leaf schema node which is added to <code>toBuilder</code> as
515 * boolean value which says if leaf property is|isn't read only
516 * @return boolean value
518 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
519 * name equals null or if leaf is added by <i>uses</i>.</li>
520 * <li>true - other cases</li>
523 static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
524 final Type returnType, final boolean isReadOnly) {
526 if (returnType == null) {
529 final String leafName = leaf.getQName().getLocalName();
530 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
531 final GeneratedPropertyBuilder propBuilder =
532 toBuilder.addProperty(NonJavaCharsConverter.convertIdentifier(leafName, JavaIdentifier.METHOD));
533 propBuilder.setReadOnly(isReadOnly);
534 propBuilder.setReturnType(returnType);
535 propBuilder.setComment(leafDesc);
536 toBuilder.addEqualsIdentity(propBuilder);
537 toBuilder.addHashIdentity(propBuilder);
538 toBuilder.addToStringProperty(propBuilder);
543 public static String replaceAllIllegalChars(final StringBuilder stringBuilder){
544 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
545 return ret.isEmpty() ? "" : ret;