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.Objects;
28 import java.util.Optional;
30 import java.util.regex.Pattern;
31 import java.util.stream.Collectors;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.eclipse.xtext.xbase.lib.StringExtensions;
34 import org.opendaylight.mdsal.binding.model.api.AnnotationType;
35 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
36 import org.opendaylight.mdsal.binding.model.api.DefaultType;
37 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
38 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
39 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
40 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
41 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
42 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
43 import org.opendaylight.mdsal.binding.model.api.Restrictions;
44 import org.opendaylight.mdsal.binding.model.api.Type;
45 import org.opendaylight.mdsal.binding.model.util.Types;
46 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
47 import org.opendaylight.yangtools.yang.binding.Augmentable;
48 import org.opendaylight.yangtools.yang.binding.CodeHelpers;
51 * Base Java file template. Contains a non-null type and imports which the generated code refers to.
53 class JavaFileTemplate {
55 * {@code java.lang.Class} as a JavaTypeName.
57 static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
59 * {@code java.lang.Deprecated} as a JavaTypeName.
61 static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
63 * {@code java.lang.NullPointerException} as a JavaTypeName.
65 static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
67 * {@code java.lang.Override} as a JavaTypeName.
69 static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
71 * {@code java.lang.void} as a JavaTypeName.
73 static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
75 * {@code java.lang.SuppressWarnings} as a JavaTypeName.
77 static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
80 * {@code java.util.Arrays} as a JavaTypeName.
82 static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
84 * {@code java.util.HashMap} as a JavaTypeName.
86 static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
88 * {@code java.util.List} as a JavaTypeName.
90 static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
92 * {@code java.util.Map} as a JavaTypeName.
94 static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
96 * {@code java.util.Objects} as a JavaTypeName.
98 static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
100 * {@code java.util.regex.Pattern} as a JavaTypeName.
102 static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
105 * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
107 static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
109 * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
111 static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
114 * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
116 static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
118 private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
119 private static final Type AUGMENTATION_RET_TYPE;
124 m = Augmentable.class.getDeclaredMethod(AUGMENTABLE_AUGMENTATION_NAME, Class.class);
125 } catch (NoSuchMethodException e) {
126 throw new ExceptionInInitializerError(e);
129 AUGMENTATION_RET_TYPE = DefaultType.of(JavaTypeName.create(m.getReturnType()));
132 private final AbstractJavaGeneratedType javaType;
133 private final GeneratedType type;
135 JavaFileTemplate(final @NonNull GeneratedType type) {
136 this(new TopLevelJavaGeneratedType(type), type);
139 JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
140 this.javaType = requireNonNull(javaType);
141 this.type = requireNonNull(type);
144 final AbstractJavaGeneratedType javaType() {
148 final GeneratedType type() {
152 final String generateImportBlock() {
153 verify(javaType instanceof TopLevelJavaGeneratedType);
154 return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
155 .collect(Collectors.joining());
158 final @NonNull String importedJavadocName(final @NonNull Type intype) {
159 return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
162 final @NonNull String importedName(final @NonNull Type intype) {
163 return javaType.getReferenceString(intype);
166 final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
167 return javaType.getReferenceString(intype, annotation);
170 final @NonNull String importedName(final Class<?> cls) {
171 return importedName(Types.typeForClass(cls));
174 final @NonNull String importedName(final @NonNull JavaTypeName intype) {
175 return javaType.getReferenceString(intype);
178 final @NonNull String importedNonNull(final @NonNull Type intype) {
179 return importedName(intype, importedName(NONNULL));
182 final @NonNull String importedNullable(final @NonNull Type intype) {
183 return importedName(intype, importedName(NULLABLE));
186 final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
187 return fullyQualifiedName(intype, importedName(NONNULL));
190 final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
191 return javaType.getFullyQualifiedReference(intype, annotation);
194 // Exposed for BuilderTemplate
195 boolean isLocalInnerClass(final JavaTypeName name) {
196 final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
197 return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
200 final CharSequence generateInnerClass(final GeneratedType innerClass) {
201 if (!(innerClass instanceof GeneratedTransferObject)) {
205 final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
206 final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
207 return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
208 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
212 * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
213 * {@link Arrays} if the property is an array, {@link Objects} otherwise.
215 * @param property Generated property
216 * @return Imported class name
218 final String importedUtilClass(final GeneratedProperty property) {
219 return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
223 * Run type analysis, which results in identification of the augmentable type, as well as all methods available
224 * to the type, expressed as properties.
226 static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
227 final Set<MethodSignature> methods = new LinkedHashSet<>();
228 final Type augmentType = createMethods(type, methods);
229 final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
232 return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
235 static final Restrictions restrictionsForSetter(final Type actualType) {
236 return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
239 static final Restrictions getRestrictions(final Type type) {
240 if (type instanceof ConcreteType) {
241 return ((ConcreteType) type).getRestrictions();
243 if (type instanceof GeneratedTransferObject) {
244 return ((GeneratedTransferObject) type).getRestrictions();
250 * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
252 * @param property Generated property
253 * @return The string used to clone the property, or an empty string
255 static final String cloneCall(final GeneratedProperty property) {
256 return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
260 * Returns set of method signature instances which contains all the methods of the <code>genType</code>
261 * and all the methods of the implemented interfaces.
263 * @returns set of method signature instances
265 private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
266 methods.addAll(type.getMethodDefinitions());
267 return collectImplementedMethods(type, methods, type.getImplements());
271 * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
272 * and recursively their implemented interfaces.
274 * @param methods set of method signatures
275 * @param implementedIfcs list of implemented interfaces
277 private static ParameterizedType collectImplementedMethods(final GeneratedType type,
278 final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
279 if (implementedIfcs == null || implementedIfcs.isEmpty()) {
283 ParameterizedType augmentType = null;
284 for (Type implementedIfc : implementedIfcs) {
285 if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
286 final GeneratedType ifc = (GeneratedType) implementedIfc;
287 addImplMethods(methods, ifc);
289 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
290 if (t != null && augmentType == null) {
293 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
294 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, DefaultType.of(type.getIdentifier()));
301 private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
302 for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
303 if (hasOverrideAnnotation(implMethod)) {
304 methods.add(implMethod);
306 final String implMethodName = implMethod.getName();
307 if (BindingMapping.isGetterMethodName(implMethodName)
308 && getterByName(methods, implMethodName).isEmpty()) {
310 methods.add(implMethod);
316 protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
317 final String implMethodName) {
318 for (MethodSignature method : methods) {
319 final String methodName = method.getName();
320 if (BindingMapping.isGetterMethodName(methodName)) {
321 if (isSameProperty(method.getName(), implMethodName)) {
322 return Optional.of(method);
326 return Optional.empty();
329 protected static String propertyNameFromGetter(final MethodSignature getter) {
330 return propertyNameFromGetter(getter.getName());
333 protected static String propertyNameFromGetter(final String getterName) {
335 if (BindingMapping.isGetterMethodName(getterName)) {
336 prefix = BindingMapping.GETTER_PREFIX;
337 } else if (BindingMapping.isNonnullMethodName(getterName)) {
338 prefix = BindingMapping.NONNULL_PREFIX;
340 throw new IllegalArgumentException(getterName + " is not a getter");
342 return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
346 * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
348 * @param method Method to examine
349 * @return True if there is an override annotation
351 static boolean hasOverrideAnnotation(final MethodSignature method) {
352 for (final AnnotationType annotation : method.getAnnotations()) {
353 if (OVERRIDE.equals(annotation.getIdentifier())) {
360 private static boolean isSameProperty(final String getterName1, final String getterName2) {
361 return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
365 * Creates set of generated property instances from getter <code>methods</code>.
367 * @param methods set of method signature instances which should be transformed to list of properties
368 * @return set of generated property instances which represents the getter <code>methods</code>
370 private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
371 if (methods == null || methods.isEmpty()) {
372 return Collections.emptySet();
374 final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
375 for (MethodSignature m : methods) {
376 final BuilderGeneratedProperty createdField = propertyFromGetter(m);
377 if (createdField != null) {
378 result.add(createdField);
385 * Creates generated property instance from the getter <code>method</code> name and return type.
387 * @param method method signature from which is the method name and return type obtained
388 * @return generated property instance for the getter <code>method</code>
389 * @throws IllegalArgumentException <ul>
390 * <li>if the <code>method</code> equals <code>null</code></li>
391 * <li>if the name of the <code>method</code> equals <code>null</code></li>
392 * <li>if the name of the <code>method</code> is empty</li>
393 * <li>if the return type of the <code>method</code> equals <code>null</code></li>
396 private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
397 checkArgument(method != null);
398 checkArgument(method.getReturnType() != null);
399 checkArgument(method.getName() != null);
400 checkArgument(!method.getName().isEmpty());
401 if (method.isDefault()) {
404 if (!BindingMapping.isGetterMethodName(method.getName())) {
408 final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX.length()));
409 return new BuilderGeneratedProperty(fieldName, method);