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.ContainerSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.Module;
55 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
56 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
57 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
58 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
59 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.Status;
61 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
69 * Auxiliary util class for {@link GenHelperUtil} class
72 final class AuxiliaryGenUtils {
74 private static final Splitter BSDOT_SPLITTER = Splitter.on(".");
75 private static final char NEW_LINE = '\n';
76 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
79 * Constant with the concrete name of identifier.
81 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
84 * Constant with the concrete name of namespace.
86 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
88 private AuxiliaryGenUtils() {
89 throw new UnsupportedOperationException("Util class");
92 static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
93 if (status == Status.DEPRECATED) {
94 builder.addAnnotation("", "Deprecated");
98 public static boolean hasBuilderClass(final SchemaNode schemaNode, final BindingNamespaceType namespaceType) {
99 if ((namespaceType.equals(BindingNamespaceType.Data)
100 && (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
101 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition))) {
107 static Constant qNameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
109 return toBuilder.addConstant(Types.typeForClass(QName.class), constantName, name);
113 * Created a method signature builder as part of
114 * <code>interfaceBuilder</code>.
116 * The method signature builder is created for the getter method of
117 * <code>schemaNodeName</code>. Also <code>comment</code> and
118 * <code>returnType</code> information are added to the builder.
120 * @param interfaceBuilder
121 * generated type builder for which the getter method should be
123 * @param schemaNodeName
124 * string with schema node name. The name will be the part of the
125 * getter method name.
127 * string with comment for the getter method
129 * type which represents the return type of the getter method
131 * status from yang file, for deprecated annotation
132 * @return method signature builder which represents the getter method of
133 * <code>interfaceBuilder</code>
135 static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
136 final String schemaNodeName, final String comment, final Type returnType, final Status status) {
138 final MethodSignatureBuilder getMethod = interfaceBuilder
139 .addMethod(getterMethodName(schemaNodeName, returnType));
140 if (status == Status.DEPRECATED) {
141 getMethod.addAnnotation("", "Deprecated");
143 getMethod.setComment(encodeAngleBrackets(comment));
144 getMethod.setReturnType(returnType);
149 * Creates the name of the getter method name from <code>localName</code>.
152 * string with the name of the getter method
155 * @return string with the name of the getter method for
156 * <code>methodName</code> in JAVA method format
158 private static String getterMethodName(final String localName, final Type returnType) {
159 final StringBuilder method = new StringBuilder();
160 if (BOOLEAN.equals(returnType)) {
163 method.append("get");
165 // underscore used as separator for distinction of method parts in convertIdentifier()
166 method.append('_').append(localName);
167 return JavaIdentifierNormalizer.normalizeSpecificIdentifier(method.toString(), JavaIdentifier.METHOD);
170 static String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName,
171 final SchemaContext schemaContext, final boolean verboseClassComments,
172 final BindingNamespaceType namespaceType) {
173 final StringBuilder sb = new StringBuilder();
174 final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
175 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
177 if (!Strings.isNullOrEmpty(formattedDescription)) {
178 sb.append(formattedDescription);
182 final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
183 if (verboseClassComments) {
185 sb.append("This class represents the following YANG schema fragment defined in module <b>");
186 sb.append(module.getName());
191 String formedYang = YangSnippetCleaner.clean(yangTemplateForNode.render(schemaNode, module).body());
192 sb.append(encodeAngleBrackets(formedYang));
195 sb.append("The schema path to identify an instance is");
198 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
202 if (hasBuilderClass(schemaNode, namespaceType) && !(schemaNode instanceof OperationDefinition)) {
203 final StringBuilder linkToBuilderClass = new StringBuilder();
204 final String basePackageName = BindingMapping.getRootPackageName(module);
207 .append(replacePackageTopNamespace(basePackageName, fullyQualifiedName,
208 namespaceType, BindingNamespaceType.Builder))
211 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
214 sb.append(linkToBuilderClass);
216 if (schemaNode instanceof ListSchemaNode) {
217 final StringBuilder linkToKeyClass = new StringBuilder();
219 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
220 final String className = namespace[namespace.length - 1];
222 linkToKeyClass.append(BindingGeneratorUtil.packageNameForSubGeneratedType(basePackageName, schemaNode,
223 BindingNamespaceType.Key))
228 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
229 if (keyDef != null && !keyDef.isEmpty()) {
231 sb.append(linkToKeyClass).append(className).append("Key");
238 return replaceAllIllegalChars(sb);
241 static String createDescription(final Module module, final boolean verboseClassComments) {
242 final StringBuilder sb = new StringBuilder();
243 final String moduleDescription = encodeAngleBrackets(module.getDescription());
244 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
246 if (!Strings.isNullOrEmpty(formattedDescription)) {
247 sb.append(formattedDescription);
251 if (verboseClassComments) {
253 sb.append("This class represents the following YANG schema fragment defined in module <b>");
254 sb.append(module.getName());
259 String formedYang = YangSnippetCleaner.clean(yangTemplateForModule.render(module).body());
260 sb.append(encodeAngleBrackets(formedYang));
264 return replaceAllIllegalChars(sb);
267 static String createDescription(final Set<? extends SchemaNode> schemaNodes, final Module module, final
268 boolean verboseClassComments) {
269 final StringBuilder sb = new StringBuilder();
271 if (!isNullOrEmpty(schemaNodes)) {
272 final SchemaNode node = schemaNodes.iterator().next();
274 if (node instanceof RpcDefinition) {
275 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + module.getName() + "</b>");
276 } else if (node instanceof NotificationDefinition) {
277 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + module.getName() + "</b>");
282 if (verboseClassComments) {
285 sb.append(encodeAngleBrackets(yangTemplateForNodes.render(schemaNodes, module).body()));
290 return replaceAllIllegalChars(sb);
293 private static boolean isNullOrEmpty(final Collection<?> list) {
294 return list == null || list.isEmpty();
298 * Returns first unique name for the augment generated type builder. The
299 * generated type builder name for augment consists from name of augmented
300 * node and serial number of its augmentation.
303 * map of builders which were created in the package to which the
304 * augmentation belongs
306 * string with name of augmented node
307 * @return string with unique name for augmentation builder
309 static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
311 if (builders != null) {
312 while (builders.containsKey(genTypeName + index)) {
316 return genTypeName + index;
320 * @param unknownSchemaNodes unknown schema nodes
321 * @return nodeParameter of UnknownSchemaNode
323 static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
324 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
325 final QName nodeType = unknownSchemaNode.getNodeType();
326 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
327 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
328 return unknownSchemaNode.getNodeParameter();
335 * Adds enumeration builder created from <code>enumTypeDef</code> to
336 * <code>typeBuilder</code>.
338 * Each <code>enumTypeDef</code> item is added to builder with its name and
342 * EnumTypeDefinition contains enum data
344 * string contains name which will be assigned to enumeration
347 * GeneratedTypeBuilder to which will be enum builder assigned
349 * Module in which type should be generated
350 * @return enumeration builder which contains data from
351 * <code>enumTypeDef</code>
353 static EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
354 final Map<Module, ModuleContext> genCtx, final GeneratedTypeBuilder typeBuilder, final Module module) {
355 if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
356 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName.getLocalName());
357 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
358 enumBuilder.setDescription(enumTypedefDescription);
359 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
360 final ModuleContext ctx = genCtx.get(module);
361 ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
369 * Builds generated TO builders for <code>typeDef</code> of type
370 * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
371 * also added to <code>typeBuilder</code> as enclosing transfer object.
373 * If more then one generated TO builder is created for enclosing then all
374 * of the generated TO builders are added to <code>typeBuilder</code> as
375 * enclosing transfer objects.
378 * type definition which can be of type <code>UnionType</code> or
379 * <code>BitsTypeDefinition</code>
381 * generated type builder to which is added generated TO created
382 * from <code>typeDef</code>
384 * string with name for generated TO builder
385 * @param parentModule
387 * @return generated TO builder for <code>typeDef</code>
389 static GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef, final GeneratedTypeBuilder
390 typeBuilder, final DataSchemaNode leaf, final Module parentModule, final TypeProvider typeProvider,
391 final SchemaContext schemaContext) {
392 final String classNameFromLeaf = leaf.getQName().getLocalName();
393 GeneratedTOBuilder genTOBuilder = null;
394 final String packageName = typeBuilder.getFullyQualifiedName();
395 if (typeDef instanceof UnionTypeDefinition) {
396 genTOBuilder = ((TypeProviderImpl) typeProvider)
397 .provideGeneratedTOBuilderForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
398 classNameFromLeaf, leaf, schemaContext,
399 ((TypeProviderImpl) typeProvider).getGenTypeDefsContextMap());
400 } else if (typeDef instanceof BitsTypeDefinition) {
401 genTOBuilder = (((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
402 packageName, typeDef, classNameFromLeaf, parentModule.getName());
404 if (genTOBuilder != null) {
405 typeBuilder.addEnclosingTransferObject(genTOBuilder);
412 @SuppressWarnings({ "unchecked", "rawtypes" })
413 static Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
414 final GeneratedTypeBuilder typeBuilder, final Module parentModule, final TypeProvider typeProvider) {
415 final GeneratedTOBuilderImpl returnType = (GeneratedTOBuilderImpl) genTOBuilder;
416 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
418 returnType.setDescription(typedefDescription);
419 returnType.setReference(typeDef.getReference());
420 returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
421 returnType.setModuleName(parentModule.getName());
423 genTOBuilder.setTypedef(true);
424 genTOBuilder.setIsUnion(true);
425 TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
427 return returnType.toInstance();
430 static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
431 if (leaf.getPath().equals(type.getPath())) {
434 if (leaf.getPath().equals(type.getPath().getParent())) {
442 * Generates for the <code>list</code> which contains any list keys special
443 * generated TO builder.
446 * string with package name to which the list belongs
448 * schema node of list
449 * @return generated TO builder which represents the keys of the
450 * <code>list</code> or empty TO builder if <code>list</code> is null or list of
451 * key definitions is null or empty.
453 static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
454 GeneratedTOBuilder genTOBuilder = null;
455 if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
456 // underscore used as separator for distinction of class name parts
457 final String genTOName =
458 new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key)
460 genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
466 * Converts <code>leaf</code> schema node to property of generated TO
470 * generated TO builder to which is <code>leaf</code> added as
473 * leaf schema node which is added to <code>toBuilder</code> as
478 * boolean value which says if leaf property is|isn't read only
479 * @return boolean value
481 * <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
482 * name equals null or if leaf is added by <i>uses</i>.</li>
483 * <li>true - other cases</li>
486 static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
487 final Type returnType, final boolean isReadOnly) {
489 if (returnType == null) {
492 final String leafName = leaf.getQName().getLocalName();
493 final String leafDesc = encodeAngleBrackets(leaf.getDescription());
494 final GeneratedPropertyBuilder propBuilder =
495 toBuilder.addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(leafName, JavaIdentifier.METHOD));
496 propBuilder.setReadOnly(isReadOnly);
497 propBuilder.setReturnType(returnType);
498 propBuilder.setComment(leafDesc);
499 toBuilder.addEqualsIdentity(propBuilder);
500 toBuilder.addHashIdentity(propBuilder);
501 toBuilder.addToStringProperty(propBuilder);
505 static void checkModuleAndModuleName(final Module module) {
506 checkArgument(module != null, "Module reference cannot be NULL.");
507 checkArgument(module.getName() != null, "Module name cannot be NULL.");
511 public static String replaceAllIllegalChars(final StringBuilder stringBuilder){
512 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
513 return ret.isEmpty() ? "" : ret;