31c651a059a847777d2ec8ca0b7a4f605da1aafe
[mdsal.git] / code-generator / binding-java-api-generator / src / main / java / org / opendaylight / yangtools / sal / java / api / generator / AbstractRangeGenerator.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.sal.java.api.generator;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableMap.Builder;
13 import java.util.Collection;
14 import java.util.Map;
15 import javax.annotation.Nonnull;
16 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
17 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
18 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
19 import org.opendaylight.yangtools.sal.binding.model.api.Type;
20 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 abstract class AbstractRangeGenerator<T extends Number & Comparable<T>> {
25     private static final Logger LOG = LoggerFactory.getLogger(AbstractRangeGenerator.class);
26     private static final Map<String, AbstractRangeGenerator<?>> GENERATORS;
27
28     private static void addGenerator(final Builder<String, AbstractRangeGenerator<?>> b, final AbstractRangeGenerator<?> generator) {
29         b.put(generator.getTypeClass().getCanonicalName(), generator);
30     }
31
32     static {
33         final Builder<String, AbstractRangeGenerator<?>> b = ImmutableMap.<String, AbstractRangeGenerator<?>> builder();
34         addGenerator(b, new ByteRangeGenerator());
35         addGenerator(b, new ShortRangeGenerator());
36         addGenerator(b, new IntegerRangeGenerator());
37         addGenerator(b, new LongRangeGenerator());
38         addGenerator(b, new BigDecimalRangeGenerator());
39         addGenerator(b, new BigIntegerRangeGenerator());
40         GENERATORS = b.build();
41     }
42
43     private final Class<T> type;
44
45     protected AbstractRangeGenerator(final Class<T> typeClass) {
46         this.type = Preconditions.checkNotNull(typeClass);
47     }
48
49     // We need to walk up the GTO tree to get the root and then return its 'value' property
50     private static Type javaTypeForGTO(final GeneratedTransferObject gto) {
51         GeneratedTransferObject rootGto = gto;
52         while (rootGto.getSuperType() != null) {
53             rootGto = rootGto.getSuperType();
54         }
55
56         LOG.debug("Root GTO of {} is {}", rootGto, gto);
57         for (GeneratedProperty s : rootGto.getProperties()) {
58             if ("value".equals(s.getName())) {
59                 return s.getReturnType();
60             }
61         }
62
63         throw new IllegalArgumentException(String.format("Failed to resolve GTO {} root {} to a Java type, properties are {}", gto, rootGto));
64     }
65
66     static AbstractRangeGenerator<?> forType(@Nonnull final Type type) {
67         final Type javaType;
68         if (type instanceof GeneratedTransferObject) {
69             javaType = javaTypeForGTO((GeneratedTransferObject) type);
70             LOG.debug("Resolved GTO {} to concrete type {}", type, javaType);
71         } else {
72             javaType = type;
73         }
74
75         Preconditions.checkArgument(javaType instanceof ConcreteType, "Unsupported type %s", type);
76         return GENERATORS.get(javaType.getFullyQualifiedName());
77     }
78
79     /**
80      * Return the type's class.
81      *
82      * @return A class object
83      */
84     protected final @Nonnull Class<T> getTypeClass() {
85         return type;
86     }
87
88     /**
89      * Return the type's fully-qualified name.
90      *
91      * @return Fully-qualified name
92      */
93     protected final @Nonnull String getTypeName() {
94         return type.getName();
95     }
96
97     /**
98      * Return the value in the native type from a particular Number instance.
99      *
100      * @param value Value as a Number
101      * @return Value in native format.
102      */
103     protected final @Nonnull T getValue(final Number value) {
104         if (type.isInstance(value)) {
105             return type.cast(value);
106         }
107
108         LOG.debug("Converting value {} from {} to {}", value, value.getClass(), type);
109         final T ret = convert(value);
110
111         // Check if the conversion lost any precision by performing conversion the other way around
112         final AbstractRangeGenerator<?> gen = GENERATORS.get(value.getClass().getName());
113         final Number check = gen.convert(ret);
114         if (!value.equals(check)) {
115             LOG.warn("Number class conversion from {} to {} truncated value {} to {}", value.getClass(), type, value, ret);
116         }
117
118         return ret;
119     }
120
121     // FIXME: Once BUG-3399 is fixed, we should never need this
122     @Deprecated
123     protected abstract T convert(final Number value);
124
125     /**
126      * Format a value into a Java-compilable expression which results in the appropriate
127      * type.
128      * @param value Number value
129      * @return Java language string representation
130      */
131     protected abstract @Nonnull String format(final T value);
132
133     /**
134      * Generate the checker method source code.
135      * @param checkerName Name of the checker method.
136      * @param constraints Restrictions which need to be applied.
137      * @return Method source code.
138      */
139     protected abstract @Nonnull String generateRangeCheckerImplementation(@Nonnull final String checkerName, @Nonnull final Collection<RangeConstraint> constraints);
140
141     private static String rangeCheckerName(final String member) {
142         return "check" + member + "Range";
143     }
144
145     String generateRangeChecker(@Nonnull final String member, @Nonnull final Collection<RangeConstraint> constraints) {
146         Preconditions.checkArgument(!constraints.isEmpty(), "Restrictions may not be empty");
147         return generateRangeCheckerImplementation(rangeCheckerName(member), constraints);
148     }
149
150     String generateRangeCheckerCall(@Nonnull final String member, @Nonnull final String valueReference) {
151         return rangeCheckerName(member) + '(' + valueReference + ");\n";
152     }
153 }