Do not generate prime when not needed
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / TypeUtils.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.mdsal.binding.java.api.generator;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import org.eclipse.jdt.annotation.NonNull;
13 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
14 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
15 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
16 import org.opendaylight.mdsal.binding.model.api.Type;
17 import org.opendaylight.mdsal.binding.model.ri.TypeConstants;
18
19 /**
20  * Random utility methods for dealing with {@link Type} objects.
21  */
22 final class TypeUtils {
23     private TypeUtils() {
24
25     }
26
27     /**
28      * Given a {@link Type} object lookup the base Java type which sits at the top
29      * of its type hierarchy.
30      *
31      * @param type Input Type object
32      * @return Resolved {@link ConcreteType} instance.
33      */
34     static ConcreteType getBaseYangType(final @NonNull Type type) {
35         // Already the correct type
36         if (type instanceof ConcreteType concrete) {
37             return concrete;
38         }
39
40         checkArgument(type instanceof GeneratedTransferObject, "Unsupported type %s", type);
41
42         // Need to walk up the GTO chain to the root
43         GeneratedTransferObject rootGto = (GeneratedTransferObject) type;
44         while (rootGto.getSuperType() != null) {
45             rootGto = rootGto.getSuperType();
46         }
47
48         // Look for the 'value' property and return its type
49         for (GeneratedProperty s : rootGto.getProperties()) {
50             if (TypeConstants.VALUE_PROP.equals(s.getName())) {
51                 return (ConcreteType) s.getReturnType();
52             }
53         }
54
55         // Should never happen
56         throw new IllegalArgumentException(String.format("Type %s root %s properties %s do not include \"%s\"",
57             type, rootGto, rootGto.getProperties(), TypeConstants.VALUE_PROP));
58     }
59
60     static Type encapsulatedValueType(final GeneratedTransferObject gto) {
61         return gto.findProperty(TypeConstants.VALUE_PROP).orElseThrow().getReturnType();
62     }
63 }