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.Types.BOOLEAN;
15 import com.google.common.annotations.Beta;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.base.Splitter;
18 import com.google.common.base.Strings;
19 import com.google.common.collect.Iterables;
20 import java.util.Collection;
21 import java.util.List;
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.txt.yangTemplateForNodes;
28 import org.opendaylight.mdsal.binding.javav2.generator.impl.util.YangTextTemplate;
29 import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
30 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier;
31 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer;
32 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
33 import org.opendaylight.mdsal.binding.javav2.generator.util.YangSnippetCleaner;
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.Constant;
37 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
38 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder;
39 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder;
40 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
41 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder;
42 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase;
43 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder;
44 import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.Module;
51 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
52 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
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 JavaIdentifierNormalizer.normalizeSpecificIdentifier(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 String formedYang = YangSnippetCleaner.clean(yangTemplateForNode.render(schemaNode, module).body());
195 sb.append(encodeAngleBrackets(formedYang));
198 sb.append("The schema path to identify an instance is");
201 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
205 if (hasBuilderClass(schemaNode) && !(schemaNode instanceof OperationDefinition)) {
207 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
210 sb.append(linkToBuilderClass);
212 if (schemaNode instanceof ListSchemaNode) {
213 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
214 if (keyDef != null && !keyDef.isEmpty()) {
216 sb.append(className);
224 return replaceAllIllegalChars(sb);
227 static String createDescription(final Module module, final boolean verboseClassComments) {
228 final StringBuilder sb = new StringBuilder();
229 final String moduleDescription = encodeAngleBrackets(module.getDescription());
230 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
232 if (!Strings.isNullOrEmpty(formattedDescription)) {
233 sb.append(formattedDescription);
237 if (verboseClassComments) {
239 sb.append("This class represents the following YANG schema fragment defined in module <b>");
240 sb.append(module.getName());
245 String formedYang = YangSnippetCleaner.clean(yangTemplateForModule.render(module).body());
246 sb.append(encodeAngleBrackets(formedYang));
250 return replaceAllIllegalChars(sb);
253 static String createDescription(final Set<? extends SchemaNode> schemaNodes, final Module module, final
254 boolean verboseClassComments) {
255 final StringBuilder sb = new StringBuilder();
257 if (!isNullOrEmpty(schemaNodes)) {
258 final SchemaNode node = schemaNodes.iterator().next();
260 if (node instanceof RpcDefinition) {
261 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + module.getName() + "</b>");
262 } else if (node instanceof NotificationDefinition) {
263 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + module.getName() + "</b>");
268 if (verboseClassComments) {
271 sb.append(encodeAngleBrackets(yangTemplateForNodes.render(schemaNodes, module).body()));
276 return replaceAllIllegalChars(sb);
279 private static boolean isNullOrEmpty(final Collection<?> list) {
280 return list == null || list.isEmpty();
284 * Returns first unique name for the augment generated type builder. The
285 * generated type builder name for augment consists from name of augmented
286 * node and serial number of its augmentation.
289 * map of builders which were created in the package to which the
290 * augmentation belongs
292 * string with name of augmented node
293 * @return string with unique name for augmentation builder
295 static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
297 if (builders != null) {
298 while (builders.containsKey(genTypeName + index)) {
302 return genTypeName + index;
306 * @param unknownSchemaNodes unknows schema nodes
307 * @return nodeParameter of UnknownSchemaNode
309 static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
310 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
311 final QName nodeType = unknownSchemaNode.getNodeType();
312 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
313 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
314 return unknownSchemaNode.getNodeParameter();
321 * Adds enumeration builder created from <code>enumTypeDef</code> to
322 * <code>typeBuilder</code>.
324 * Each <code>enumTypeDef</code> item is added to builder with its name and
328 * EnumTypeDefinition contains enum data
330 * string contains name which will be assigned to enumeration
333 * GeneratedTypeBuilder to which will be enum builder assigned
335 * Module in which type should be generated
336 * @return enumeration builder which contains data from
337 * <code>enumTypeDef</code>
339 static EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
340 final Map<Module, ModuleContext> genCtx, final GeneratedTypeBuilder typeBuilder, final Module module) {
341 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
342 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName.getLocalName());
343 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
344 enumBuilder.setDescription(enumTypedefDescription);
345 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
346 final ModuleContext ctx = genCtx.get(module);
347 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
355 * Builds generated TO builders for <code>typeDef</code> of type
356 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
357 * also added to <code>typeBuilder</code> as enclosing transfer object.
359 * If more then one generated TO builder is created for enclosing then all
360 * of the generated TO builders are added to <code>typeBuilder</code> as
361 * enclosing transfer objects.
364 * type definition which can be of type <code>UnionType</code> or
365 * <code>BitsTypeDefinition</code>
367 * generated type builder to which is added generated TO created
368 * from <code>typeDef</code>
370 * string with name for generated TO builder
371 * @param parentModule
373 * @return generated TO builder for <code>typeDef</code>
375 static GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef, final GeneratedTypeBuilder
376 typeBuilder, final DataSchemaNode leaf, final Module parentModule, final TypeProvider typeProvider,
377 final SchemaContext schemaContext) {
378 final String classNameFromLeaf = leaf.getQName().getLocalName();
379 GeneratedTOBuilder genTOBuilder = null;
380 final String packageName = typeBuilder.getFullyQualifiedName();
381 if (typeDef instanceof UnionTypeDefinition) {
382 genTOBuilder = ((TypeProviderImpl) typeProvider)
383 .provideGeneratedTOBuilderForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
384 classNameFromLeaf, leaf, schemaContext,
385 ((TypeProviderImpl) typeProvider).getGenTypeDefsContextMap());
386 } else if (typeDef instanceof BitsTypeDefinition) {
387 genTOBuilder = (((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
388 packageName, typeDef, classNameFromLeaf, parentModule.getName());
390 if (genTOBuilder != null) {
391 typeBuilder.addEnclosingTransferObject(genTOBuilder);
398 @SuppressWarnings({ "unchecked", "rawtypes" })
399 static Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
400 final GeneratedTypeBuilder typeBuilder, final Module parentModule, final TypeProvider typeProvider) {
401 final GeneratedTOBuilderImpl returnType = (GeneratedTOBuilderImpl) genTOBuilder;
402 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
404 returnType.setDescription(typedefDescription);
405 returnType.setReference(typeDef.getReference());
406 returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
407 returnType.setModuleName(parentModule.getName());
409 genTOBuilder.setTypedef(true);
410 genTOBuilder.setIsUnion(true);
411 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
413 return returnType.toInstance();
416 static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
417 if (leaf.getPath().equals(type.getPath())) {
420 if (leaf.getPath().equals(type.getPath().getParent())) {
428 * Generates for the <code>list</code> which contains any list keys special
429 * generated TO builder.
432 * string with package name to which the list belongs
434 * schema node of list
435 * @return generated TO builder which represents the keys of the
436 * <code>list</code> or empty TO builder if <code>list</code> is null or list of
437 * key definitions is null or empty.
439 static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
440 GeneratedTOBuilder genTOBuilder = null;
441 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
442 // underscore used as separator for distinction of class name parts
443 final String genTOName =
444 new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key)
447 new GeneratedTOBuilderImpl(new StringBuilder(packageName).toString(), genTOName);
453 * Converts <code>leaf</code> schema node to property of generated TO
457 * generated TO builder to which is <code>leaf</code> added as
460 * leaf schema node which is added to <code>toBuilder</code> as
465 * boolean value which says if leaf property is|isn't read only
466 * @return boolean value
468 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
469 * name equals null or if leaf is added by <i>uses</i>.</li>
470 * <li>true - other cases</li>
473 static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
474 final Type returnType, final boolean isReadOnly) {
476 if (returnType == null) {
479 final String leafName = leaf.getQName().getLocalName();
480 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
481 final GeneratedPropertyBuilder propBuilder =
482 toBuilder.addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(leafName, JavaIdentifier.METHOD));
483 propBuilder.setReadOnly(isReadOnly);
484 propBuilder.setReturnType(returnType);
485 propBuilder.setComment(leafDesc);
486 toBuilder.addEqualsIdentity(propBuilder);
487 toBuilder.addHashIdentity(propBuilder);
488 toBuilder.addToStringProperty(propBuilder);
492 static void checkModuleAndModuleName(final Module module) {
493 checkArgument(module != null, "Module reference cannot be NULL.");
494 checkArgument(module.getName() != null, "Module name cannot be NULL.");
498 public static String replaceAllIllegalChars(final StringBuilder stringBuilder){
499 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
500 return ret.isEmpty() ? "" : ret;