Speed up AbstractBuilderTemplate.removeProperty()
[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
18 /**
19  * Random utility methods for dealing with {@link Type} objects.
20  */
21 final class TypeUtils {
22     private static final String VALUE_PROP = "value";
23
24     private TypeUtils() {
25         throw new UnsupportedOperationException();
26     }
27
28     /**
29      * Given a {@link Type} object lookup the base Java type which sits at the top
30      * of its type hierarchy.
31      *
32      * @param type Input Type object
33      * @return Resolved {@link ConcreteType} instance.
34      */
35     static ConcreteType getBaseYangType(final @NonNull Type type) {
36         // Already the correct type
37         if (type instanceof ConcreteType) {
38             return (ConcreteType) type;
39         }
40
41         checkArgument(type instanceof GeneratedTransferObject, "Unsupported type %s", type);
42
43         // Need to walk up the GTO chain to the root
44         GeneratedTransferObject rootGto = (GeneratedTransferObject) type;
45         while (rootGto.getSuperType() != null) {
46             rootGto = rootGto.getSuperType();
47         }
48
49         // Look for the 'value' property and return its type
50         for (GeneratedProperty s : rootGto.getProperties()) {
51             if (VALUE_PROP.equals(s.getName())) {
52                 return (ConcreteType) s.getReturnType();
53             }
54         }
55
56         // Should never happen
57         throw new IllegalArgumentException(String.format("Type %s root %s properties %s do not include \"%s\"",
58             type, rootGto, rootGto.getProperties(), VALUE_PROP));
59     }
60 }