2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. 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
8 package org.opendaylight.mdsal.binding.java.api.generator;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTABLE_AUGMENTATION_NAME;
14 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.GETTER_PREFIX;
16 import com.google.common.collect.ImmutableSortedSet;
17 import java.lang.reflect.Method;
18 import java.util.AbstractMap;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Comparator;
23 import java.util.HashMap;
24 import java.util.LinkedHashSet;
25 import java.util.List;
27 import java.util.NoSuchElementException;
28 import java.util.Objects;
29 import java.util.Optional;
31 import java.util.regex.Pattern;
32 import java.util.stream.Collectors;
33 import javax.annotation.processing.Generated;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.eclipse.xtext.xbase.lib.StringExtensions;
36 import org.opendaylight.mdsal.binding.model.api.AnnotationType;
37 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
38 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
39 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
41 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
42 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
43 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
44 import org.opendaylight.mdsal.binding.model.api.Restrictions;
45 import org.opendaylight.mdsal.binding.model.api.Type;
46 import org.opendaylight.mdsal.binding.model.ri.Types;
47 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
48 import org.opendaylight.yangtools.yang.binding.Augmentable;
49 import org.opendaylight.yangtools.yang.binding.CodeHelpers;
52 * Base Java file template. Contains a non-null type and imports which the generated code refers to.
54 class JavaFileTemplate {
56 * {@code java.lang.Class} as a JavaTypeName.
58 static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
60 * {@code java.lang.Deprecated} as a JavaTypeName.
62 static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
64 * {@code java.lang.NullPointerException} as a JavaTypeName.
66 static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
68 * {@code java.lang.NoSuchElementException} as a JavaTypeName.
70 static final @NonNull JavaTypeName NSEE = JavaTypeName.create(NoSuchElementException.class);
72 * {@code java.lang.Override} as a JavaTypeName.
74 static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
76 * {@code java.lang.void} as a JavaTypeName.
78 static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
80 * {@code java.lang.SuppressWarnings} as a JavaTypeName.
82 static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
85 * {@code java.util.Arrays} as a JavaTypeName.
87 static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
89 * {@code java.util.HashMap} as a JavaTypeName.
91 static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
93 * {@code java.util.List} as a JavaTypeName.
95 static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
97 * {@code java.util.Map} as a JavaTypeName.
99 static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
101 * {@code java.util.Objects} as a JavaTypeName.
103 static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
105 * {@code java.util.regex.Pattern} as a JavaTypeName.
107 static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
110 * {@code javax.annotation.processing.Generated} as a JavaTypeName.
112 static final @NonNull JavaTypeName GENERATED = JavaTypeName.create(Generated.class);
115 * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
117 static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
119 * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
121 static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
124 * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
126 static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
128 private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
129 private static final Type AUGMENTATION_RET_TYPE;
134 m = Augmentable.class.getDeclaredMethod(AUGMENTABLE_AUGMENTATION_NAME, Class.class);
135 } catch (NoSuchMethodException e) {
136 throw new ExceptionInInitializerError(e);
139 AUGMENTATION_RET_TYPE = Type.of(JavaTypeName.create(m.getReturnType()));
142 private final AbstractJavaGeneratedType javaType;
143 private final GeneratedType type;
145 JavaFileTemplate(final @NonNull GeneratedType type) {
146 this(new TopLevelJavaGeneratedType(type), type);
149 JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
150 this.javaType = requireNonNull(javaType);
151 this.type = requireNonNull(type);
154 final AbstractJavaGeneratedType javaType() {
158 final GeneratedType type() {
162 final String generateImportBlock() {
163 verify(javaType instanceof TopLevelJavaGeneratedType);
164 return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
165 .collect(Collectors.joining());
168 final @NonNull String importedJavadocName(final @NonNull Type intype) {
169 return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
172 final @NonNull String importedName(final @NonNull Type intype) {
173 return javaType.getReferenceString(intype);
176 final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
177 return javaType.getReferenceString(intype, annotation);
180 final @NonNull String importedName(final Class<?> cls) {
181 return importedName(Types.typeForClass(cls));
184 final @NonNull String importedName(final @NonNull JavaTypeName intype) {
185 return javaType.getReferenceString(intype);
188 final @NonNull String importedNonNull(final @NonNull Type intype) {
189 return importedName(intype, importedName(NONNULL));
192 final @NonNull String importedNullable(final @NonNull Type intype) {
193 return importedName(intype, importedName(NULLABLE));
196 final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
197 return fullyQualifiedName(intype, importedName(NONNULL));
200 final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
201 return javaType.getFullyQualifiedReference(intype, annotation);
204 // Exposed for BuilderTemplate
205 boolean isLocalInnerClass(final JavaTypeName name) {
206 final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
207 return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
210 final CharSequence generateInnerClass(final GeneratedType innerClass) {
211 if (!(innerClass instanceof GeneratedTransferObject)) {
215 final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
216 final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
217 return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
218 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
222 * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
223 * {@link Arrays} if the property is an array, {@link Objects} otherwise.
225 * @param property Generated property
226 * @return Imported class name
228 final String importedUtilClass(final GeneratedProperty property) {
229 return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
232 final String generatedAnnotation() {
233 return "@" + importedName(GENERATED) + "(\"mdsal-binding-generator\")";
237 * Run type analysis, which results in identification of the augmentable type, as well as all methods available
238 * to the type, expressed as properties.
240 static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
241 final Set<MethodSignature> methods = new LinkedHashSet<>();
242 final Type augmentType = createMethods(type, methods);
243 final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
246 return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
249 static final Restrictions restrictionsForSetter(final Type actualType) {
250 return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
253 static final Restrictions getRestrictions(final Type type) {
254 if (type instanceof ConcreteType) {
255 return ((ConcreteType) type).getRestrictions();
257 if (type instanceof GeneratedTransferObject) {
258 return ((GeneratedTransferObject) type).getRestrictions();
264 * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
266 * @param property Generated property
267 * @return The string used to clone the property, or an empty string
269 static final String cloneCall(final GeneratedProperty property) {
270 return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
274 * Returns set of method signature instances which contains all the methods of the <code>genType</code>
275 * and all the methods of the implemented interfaces.
277 * @returns set of method signature instances
279 private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
280 methods.addAll(type.getMethodDefinitions());
281 return collectImplementedMethods(type, methods, type.getImplements());
285 * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
286 * and recursively their implemented interfaces.
288 * @param methods set of method signatures
289 * @param implementedIfcs list of implemented interfaces
291 private static ParameterizedType collectImplementedMethods(final GeneratedType type,
292 final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
293 if (implementedIfcs == null || implementedIfcs.isEmpty()) {
297 ParameterizedType augmentType = null;
298 for (Type implementedIfc : implementedIfcs) {
299 if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
300 final GeneratedType ifc = (GeneratedType) implementedIfc;
301 addImplMethods(methods, ifc);
303 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
304 if (t != null && augmentType == null) {
307 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
308 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, Type.of(type.getIdentifier()));
315 private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
316 for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
317 if (hasOverrideAnnotation(implMethod)) {
318 methods.add(implMethod);
320 final String implMethodName = implMethod.getName();
321 if (BindingMapping.isGetterMethodName(implMethodName)
322 && getterByName(methods, implMethodName).isEmpty()) {
324 methods.add(implMethod);
330 protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
331 final String implMethodName) {
332 for (MethodSignature method : methods) {
333 final String methodName = method.getName();
334 if (BindingMapping.isGetterMethodName(methodName) && isSameProperty(method.getName(), implMethodName)) {
335 return Optional.of(method);
338 return Optional.empty();
341 protected static String propertyNameFromGetter(final MethodSignature getter) {
342 return propertyNameFromGetter(getter.getName());
345 protected static String propertyNameFromGetter(final String getterName) {
347 if (BindingMapping.isGetterMethodName(getterName)) {
348 prefix = BindingMapping.GETTER_PREFIX;
349 } else if (BindingMapping.isNonnullMethodName(getterName)) {
350 prefix = BindingMapping.NONNULL_PREFIX;
351 } else if (BindingMapping.isRequireMethodName(getterName)) {
352 prefix = BindingMapping.REQUIRE_PREFIX;
354 throw new IllegalArgumentException(getterName + " is not a getter");
356 return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
360 * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
362 * @param method Method to examine
363 * @return True if there is an override annotation
365 static boolean hasOverrideAnnotation(final MethodSignature method) {
366 for (final AnnotationType annotation : method.getAnnotations()) {
367 if (OVERRIDE.equals(annotation.getIdentifier())) {
374 private static boolean isSameProperty(final String getterName1, final String getterName2) {
375 return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
379 * Creates set of generated property instances from getter <code>methods</code>.
381 * @param methods set of method signature instances which should be transformed to list of properties
382 * @return set of generated property instances which represents the getter <code>methods</code>
384 private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
385 if (methods == null || methods.isEmpty()) {
386 return Collections.emptySet();
388 final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
389 for (MethodSignature m : methods) {
390 final BuilderGeneratedProperty createdField = propertyFromGetter(m);
391 if (createdField != null) {
392 result.add(createdField);
399 * Creates generated property instance from the getter <code>method</code> name and return type.
401 * @param method method signature from which is the method name and return type obtained
402 * @return generated property instance for the getter <code>method</code>
403 * @throws IllegalArgumentException <ul>
404 * <li>if the {@code method} equals {@code null}</li>
405 * <li>if the name of the {@code method} equals {@code null}</li>
406 * <li>if the name of the {@code method} is empty</li>
407 * <li>if the return type of the {@code method} equals {@code null}</li>
410 private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
411 checkArgument(method != null);
412 checkArgument(method.getReturnType() != null);
413 checkArgument(method.getName() != null);
414 checkArgument(!method.getName().isEmpty());
415 if (method.isDefault()) {
418 if (!BindingMapping.isGetterMethodName(method.getName())) {
422 final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX.length()));
423 return new BuilderGeneratedProperty(fieldName, method);