2 * Copyright (c) 2014 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
8 package org.opendaylight.mdsal.binding.model.util;
10 import com.google.common.base.CharMatcher;
11 import com.google.common.collect.Collections2;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableList.Builder;
14 import com.google.common.collect.Iterables;
15 import java.io.ByteArrayOutputStream;
16 import java.io.DataOutputStream;
17 import java.io.IOException;
18 import java.security.MessageDigest;
19 import java.security.NoSuchAlgorithmException;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.regex.Pattern;
28 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
29 import org.opendaylight.mdsal.binding.model.api.Restrictions;
30 import org.opendaylight.mdsal.binding.model.api.Type;
31 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
32 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
33 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
34 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
35 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
38 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
42 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
43 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
44 import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
47 import org.opendaylight.yangtools.yang.model.util.type.DecimalTypeBuilder;
50 * Contains the methods for converting strings to valid JAVA language strings
51 * (package names, class names, attribute names) and to valid javadoc comments.
53 public final class BindingGeneratorUtil {
56 * Impossible to instantiate this class. All of the methods or attributes are static.
58 private BindingGeneratorUtil() {
63 * Pre-compiled replacement pattern.
65 private static final CharMatcher DASH_COLON_MATCHER = CharMatcher.anyOf("-:");
66 private static final CharMatcher GT_MATCHER = CharMatcher.is('>');
67 private static final CharMatcher LT_MATCHER = CharMatcher.is('<');
68 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
70 private static final Restrictions EMPTY_RESTRICTIONS = new Restrictions() {
72 public Optional<LengthConstraint> getLengthConstraint() {
73 return Optional.empty();
77 public List<PatternConstraint> getPatternConstraints() {
78 return Collections.emptyList();
82 public Optional<RangeConstraint<?>> getRangeConstraint() {
83 return Optional.empty();
87 public boolean isEmpty() {
92 private static final Comparator<TypeMemberBuilder<?>> SUID_MEMBER_COMPARATOR =
93 Comparator.comparing(TypeMemberBuilder::getName);
95 private static final Comparator<Type> SUID_NAME_COMPARATOR = Comparator.comparing(Type::getFullyQualifiedName);
98 * Converts <code>parameterName</code> to valid JAVA parameter name. If the <code>parameterName</code> is one
99 * of the JAVA reserved words then it is prefixed with underscore character.
101 * @param parameterName string with the parameter name
102 * @return string with the admissible parameter name
104 public static String resolveJavaReservedWordEquivalency(final String parameterName) {
105 if (parameterName != null && BindingMapping.JAVA_RESERVED_WORDS.contains(parameterName)) {
106 return "_" + parameterName;
108 return parameterName;
112 * Creates package name from specified <code>basePackageName</code> (package name for module)
113 * and <code>schemaPath</code>. Resulting package name is concatenation of <code>basePackageName</code>
114 * and all local names of YANG nodes which are parents of some node for which <code>schemaPath</code> is specified.
116 * @param basePackageName string with package name of the module, MUST be normalized, otherwise this method may
117 * return an invalid string.
118 * @param schemaPath list of names of YANG nodes which are parents of some node + name of this node
119 * @return string with valid JAVA package name
120 * @throws NullPointerException if any of the arguments are null
122 public static String packageNameForGeneratedType(final String basePackageName, final SchemaPath schemaPath) {
123 final int size = Iterables.size(schemaPath.getPathTowardsRoot()) - 1;
125 return basePackageName;
128 return generateNormalizedPackageName(basePackageName, schemaPath.getPathFromRoot(), size);
132 * Creates package name from specified <code>basePackageName</code> (package name for module)
133 * and <code>schemaPath</code> which crosses an augmentation. Resulting package name is concatenation
134 * of <code>basePackageName</code> and all local names of YANG nodes which are parents of some node for which
135 * <code>schemaPath</code> is specified.
137 * @param basePackageName string with package name of the module, MUST be normalized, otherwise this method may
138 * return an invalid string.
139 * @param schemaPath list of names of YANG nodes which are parents of some node + name of this node
140 * @return string with valid JAVA package name
141 * @throws NullPointerException if any of the arguments are null
143 public static String packageNameForAugmentedGeneratedType(final String basePackageName,
144 final SchemaPath schemaPath) {
145 final int size = Iterables.size(schemaPath.getPathTowardsRoot());
147 return basePackageName;
150 return generateNormalizedPackageName(basePackageName, schemaPath.getPathFromRoot(), size);
153 private static String generateNormalizedPackageName(final String base, final Iterable<QName> path, final int size) {
154 final StringBuilder builder = new StringBuilder(base);
155 final Iterator<QName> iterator = path.iterator();
156 for (int i = 0; i < size; ++i) {
158 final String nodeLocalName = iterator.next().getLocalName();
159 // FIXME: Collon ":" is invalid in node local name as per RFC6020, identifier statement.
160 builder.append(DASH_COLON_MATCHER.replaceFrom(nodeLocalName, '.'));
162 return BindingMapping.normalizePackageName(builder.toString());
165 private static <T> Iterable<T> sortedCollection(final Comparator<? super T> comparator, final Collection<T> input) {
166 if (input.size() <= 1) {
170 final List<T> ret = new ArrayList<>(input);
171 ret.sort(comparator);
175 private static final ThreadLocal<MessageDigest> SHA1_MD = ThreadLocal.withInitial(() -> {
177 return MessageDigest.getInstance("SHA");
178 } catch (final NoSuchAlgorithmException e) {
179 throw new IllegalStateException("Failed to get a SHA digest provider", e);
183 public static long computeDefaultSUID(final GeneratedTypeBuilderBase<?> to) {
184 final ByteArrayOutputStream bout = new ByteArrayOutputStream();
185 try (DataOutputStream dout = new DataOutputStream(bout)) {
186 dout.writeUTF(to.getName());
187 dout.writeInt(to.isAbstract() ? 3 : 7);
189 for (final Type ifc : sortedCollection(SUID_NAME_COMPARATOR, filteredImplementsTypes(to))) {
190 dout.writeUTF(ifc.getFullyQualifiedName());
193 for (final GeneratedPropertyBuilder gp : sortedCollection(SUID_MEMBER_COMPARATOR, to.getProperties())) {
194 dout.writeUTF(gp.getName());
197 for (final MethodSignatureBuilder m : sortedCollection(SUID_MEMBER_COMPARATOR, to.getMethodDefinitions())) {
198 if (!m.getAccessModifier().equals(AccessModifier.PRIVATE)) {
199 dout.writeUTF(m.getName());
200 dout.write(m.getAccessModifier().ordinal());
205 } catch (final IOException e) {
206 throw new IllegalStateException("Failed to hash object " + to, e);
209 final byte[] hashBytes = SHA1_MD.get().digest(bout.toByteArray());
211 for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
212 hash = hash << 8 | hashBytes[i] & 0xFF;
217 private static Collection<Type> filteredImplementsTypes(final GeneratedTypeBuilderBase<?> to) {
218 return Collections2.filter(to.getImplementsTypes(), item -> !BindingTypes.TYPE_OBJECT.equals(item));
221 private static <T extends Optional<?>> T currentOrEmpty(final T current, final T base) {
222 return current.equals(base) ? (T)Optional.empty() : current;
225 private static boolean containsConstraint(final StringTypeDefinition type, final PatternConstraint constraint) {
226 for (StringTypeDefinition wlk = type; wlk != null; wlk = wlk.getBaseType()) {
227 if (wlk.getPatternConstraints().contains(constraint)) {
235 private static List<PatternConstraint> uniquePatterns(final StringTypeDefinition type) {
236 final List<PatternConstraint> constraints = type.getPatternConstraints();
237 if (constraints.isEmpty()) {
241 final Builder<PatternConstraint> builder = ImmutableList.builder();
242 boolean filtered = false;
243 for (final PatternConstraint c : constraints) {
244 if (containsConstraint(type.getBaseType(), c)) {
251 return filtered ? builder.build() : constraints;
254 public static Restrictions getRestrictions(final TypeDefinition<?> type) {
255 // Old parser generated types which actually contained based restrictions, but our code deals with that when
256 // binding to core Java types. Hence we'll emit empty restrictions for base types.
257 if (type == null || type.getBaseType() == null) {
258 // Handling of decimal64 has changed in the new parser. It contains range restrictions applied to the type
259 // directly, without an extended type. We need to capture such constraints. In order to retain behavior we
260 // need to analyze the new semantics and see if the constraints have been overridden. To do that we
261 // instantiate a temporary unconstrained type and compare them.
263 // FIXME: looking at the generated code it looks as though we need to pass the restrictions without
265 if (type instanceof DecimalTypeDefinition) {
266 final DecimalTypeDefinition decimal = (DecimalTypeDefinition) type;
267 final DecimalTypeBuilder tmpBuilder = BaseTypes.decimalTypeBuilder(decimal.getPath());
268 tmpBuilder.setFractionDigits(decimal.getFractionDigits());
269 final DecimalTypeDefinition tmp = tmpBuilder.build();
271 if (!tmp.getRangeConstraint().equals(decimal.getRangeConstraint())) {
272 return new Restrictions() {
274 public boolean isEmpty() {
279 public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
280 return decimal.getRangeConstraint();
284 public List<PatternConstraint> getPatternConstraints() {
285 return ImmutableList.of();
289 public Optional<LengthConstraint> getLengthConstraint() {
290 return Optional.empty();
296 return EMPTY_RESTRICTIONS;
299 final Optional<LengthConstraint> length;
300 final List<PatternConstraint> pattern;
301 final Optional<? extends RangeConstraint<?>> range;
304 * Take care of extended types.
306 * Other types which support constraints are check afterwards. There is a slight twist with them, as returned
307 * constraints are the effective view, e.g. they are inherited from base type. Since the constraint is already
308 * enforced by the base type, we want to skip them and not perform duplicate checks.
310 * We end up emitting ConcreteType instances for YANG base types, which leads to their constraints not being
311 * enforced (most notably decimal64). Therefore we need to make sure we do not strip the next-to-last
314 * FIXME: this probably not the best solution and needs further analysis.
316 if (type instanceof BinaryTypeDefinition) {
317 final BinaryTypeDefinition binary = (BinaryTypeDefinition)type;
318 final BinaryTypeDefinition base = binary.getBaseType();
319 if (base != null && base.getBaseType() != null) {
320 length = currentOrEmpty(binary.getLengthConstraint(), base.getLengthConstraint());
322 length = binary.getLengthConstraint();
325 pattern = ImmutableList.of();
326 range = Optional.empty();
327 } else if (type instanceof DecimalTypeDefinition) {
328 length = Optional.empty();
329 pattern = ImmutableList.of();
331 final DecimalTypeDefinition decimal = (DecimalTypeDefinition)type;
332 final DecimalTypeDefinition base = decimal.getBaseType();
333 if (base != null && base.getBaseType() != null) {
334 range = currentOrEmpty(decimal.getRangeConstraint(), base.getRangeConstraint());
336 range = decimal.getRangeConstraint();
338 } else if (type instanceof RangeRestrictedTypeDefinition) {
339 // Integer-like types
340 length = Optional.empty();
341 pattern = ImmutableList.of();
342 range = extractRangeConstraint((RangeRestrictedTypeDefinition<?, ?>)type);
343 } else if (type instanceof StringTypeDefinition) {
344 final StringTypeDefinition string = (StringTypeDefinition)type;
345 final StringTypeDefinition base = string.getBaseType();
346 if (base != null && base.getBaseType() != null) {
347 length = currentOrEmpty(string.getLengthConstraint(), base.getLengthConstraint());
349 length = string.getLengthConstraint();
352 pattern = uniquePatterns(string);
353 range = Optional.empty();
355 length = Optional.empty();
356 pattern = ImmutableList.of();
357 range = Optional.empty();
360 // Now, this may have ended up being empty, too...
361 if (!length.isPresent() && pattern.isEmpty() && !range.isPresent()) {
362 return EMPTY_RESTRICTIONS;
365 // Nope, not empty allocate a holder
366 return new Restrictions() {
368 public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
373 public List<PatternConstraint> getPatternConstraints() {
378 public Optional<LengthConstraint> getLengthConstraint() {
383 public boolean isEmpty() {
389 private static <T extends RangeRestrictedTypeDefinition<?, ?>> Optional<? extends RangeConstraint<?>>
390 extractRangeConstraint(final T def) {
391 final T base = (T) def.getBaseType();
392 if (base != null && base.getBaseType() != null) {
393 return currentOrEmpty(def.getRangeConstraint(), base.getRangeConstraint());
396 return def.getRangeConstraint();
400 * Encodes angle brackets in yang statement description.
402 * @param description description of a yang statement which is used to generate javadoc comments
403 * @return string with encoded angle brackets
405 public static String encodeAngleBrackets(String description) {
406 if (description != null) {
407 description = LT_MATCHER.replaceFrom(description, "<");
408 description = GT_MATCHER.replaceFrom(description, ">");
413 public static String replaceAllIllegalChars(final CharSequence stringBuilder) {
414 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
415 return ret.isEmpty() ? "" : ret;