aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapperHelper.java
blob: a2afab0a8b9d1f6bc8890414c9599e707c03ac09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/*
 * ============LICENSE_START=======================================================
 * ONAP : ccsdk features
 * ================================================================================
 * Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
 * All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 *
 */
package org.onap.ccsdk.features.sdnr.wt.dataprovider.yangtools;

import com.fasterxml.jackson.databind.DeserializationContext;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nullable;
import org.opendaylight.yangtools.concepts.Builder;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class YangToolsMapperHelper {

    private static final Logger LOG = LoggerFactory.getLogger(YangToolsMapperHelper.class);
    private static final String TYPEOBJECT_INSTANCE_METHOD = "getDefaultInstance";
    private static final String BUILDER = "Builder";

    private static BundleContext context = getBundleContext();
    private static ConcurrentHashMap<String, Class<?>> cache = new ConcurrentHashMap<>();

    private YangToolsMapperHelper() {
        //Make unaccessible
    }

    public static Class<?> findClass(String name) throws ClassNotFoundException {

        //Try first in cache
        Class<?> res = cache.get(name);
        if (res != null) {
            return res;
        }
        //Try first in actual bundle
        try {
            return loadClass(null, name);
        } catch (ClassNotFoundException e) {
            // No problem, this bundle doesn't have the class
        }
        // Try to find in other bundles
        if (context != null) {
            //OSGi environment
            for (Bundle b : context.getBundles()) {
                try {
                    return loadClass(b, name);
                } catch (ClassNotFoundException e) {
                    // No problem, this bundle doesn't have the class
                }
            }
        }
        // really not found in any bundle
        throw new ClassNotFoundException("Can not find class '"+name+"'");
    }

    private static Class<?> loadClass(Bundle b, String name) throws ClassNotFoundException {
        Class<?> res = b == null ? Class.forName(name) : b.loadClass(name);
        cache.put(name, res);
        return res;
    }

    /**
     * Verify if builder is available
     *
     * @throws ClassNotFoundException
     **/
    public static Class<?> assertBuilderClass(Class<?> clazz) throws ClassNotFoundException {
        return getBuilderClass(getBuilderClassName(clazz));
    }

    public static Class<?> getBuilderClass(String name) throws ClassNotFoundException {
        return findClass(name);
    }

    public static Class<?> getBuilderClass(Class<?> clazz) throws ClassNotFoundException {
        return findClass(getBuilderClassName(clazz));
    }

    /**
     * Create name of builder class
     *
     * @param <T>
     * @param clazz
     * @return builders class name
     * @throws ClassNotFoundException
     */
    public static String getBuilderClassName(Class<?> clazz) {
        return clazz.getName() + BUILDER;
    }

    @SuppressWarnings("unchecked")
    public static <B extends Builder<?>> Class<B> findBuilderClass(DeserializationContext ctxt, Class<?> clazz) throws ClassNotFoundException {
        return (Class<B>) findClass(getBuilderClassName(clazz));
    }

    public static <B extends Builder<?>> Optional<Class<B>> findBuilderClassOptional(DeserializationContext ctxt, Class<?> clazz) {
        try {
            return Optional.of(findBuilderClass(ctxt, clazz));
        } catch (ClassNotFoundException e) {
            return Optional.empty();
        }
    }

    public static boolean hasClassDeclaredMethod(Class<?> clazz, String name) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method m : methods) {
            if (m.getName().equals(name)) {
                return true;
            }
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    public static <T> Optional<T> getInstanceByConstructor(Class<?> clazz, String arg) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
        List<Class<?>> ctypes = getConstructorParameterTypes(clazz, String.class);
        Optional<Object> oObj;
        for (Class<?> ctype : ctypes) {
            if (ctype.equals(String.class)) {
                return Optional.of((T) clazz.getConstructor(ctype).newInstance(arg));
            } else if ((oObj = getDefaultInstance(ctype, arg)).isPresent()) {
                return Optional.of((T) clazz.getConstructor(ctype).newInstance(oObj.get()));
            } else {
                // TODO: recursive instantiation down to string constructor or
                // getDefaultInstance method
                LOG.debug("Not implemented arg:'{}' class:'{}'", arg, clazz);
            }
        }
        return Optional.empty();
    }

    @SuppressWarnings("unchecked")
    public static <T> Optional<T> getDefaultInstance(@Nullable Class<?> clazz, String arg)
            throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {
        LOG.trace("arg:'{}' clazz '{}'", arg, clazz.getName());
        if (clazz != null) {
            Method[] methods = clazz.getDeclaredMethods();
            for (Method m : methods) {
                //TODO Verify argument type to avoid exception
                if (m.getName().equals(TYPEOBJECT_INSTANCE_METHOD)) {
                    Method method = clazz.getDeclaredMethod(TYPEOBJECT_INSTANCE_METHOD, String.class);
                    LOG.trace("Invoke {} available {}",TYPEOBJECT_INSTANCE_METHOD, method != null);
                    return Optional.of((T) method.invoke(null, arg));
                }
            }
        }
        return Optional.empty();
    }

    public static <T> Optional<T> getDefaultInstance(Optional<Class<T>> optionalClazz, String arg)
            throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {
        if (optionalClazz.isPresent()) {
            return getDefaultInstance(optionalClazz.get(), arg);
        }
        return Optional.empty();
    }

    public static List<Class<?>> getConstructorParameterTypes(Class<?> clazz, Class<?> prefer) {

        Constructor<?>[] constructors = clazz.getConstructors();
        List<Class<?>> res = new ArrayList<>();
        for (Constructor<?> c : constructors) {
            Class<?>[] ptypes = c.getParameterTypes();
            if (ptypes.length == 1) {
                res.add(ptypes[0]);
            }

            if (prefer != null && ptypes.length == 1 && ptypes[0].equals(prefer)) {
                return Arrays.asList(prefer);
            }
        }
        return res;
    }

    public static boolean implementsInterface(Class<?> clz, Class<?> ifToImplement) {
        Class<?>[] ifs = clz.getInterfaces();
        for (Class<?> iff : ifs) {
            if (iff.equals(ifToImplement)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Provide mapping of string to attribute names, generated by yang-tools. "netconf-id" converted to "_netconfId"
     *
     * @param name with attribute name, not null or empty
     * @return converted string or null if name was empty or null
     */
    public @Nullable static String toCamelCaseAttributeName(final String name) {
        if (name == null || name.isEmpty())
            return null;

        final StringBuilder ret = new StringBuilder(name.length());
        if (!name.startsWith("_"))
            ret.append('_');
        int start = 0;
        for (final String word : name.split("-")) {
            if (!word.isEmpty()) {
                if (start++ == 0) {
                    ret.append(Character.toLowerCase(word.charAt(0)));
                } else {
                    ret.append(Character.toUpperCase(word.charAt(0)));
                }
                ret.append(word.substring(1));
            }
        }
        return ret.toString();
    }

    private static BundleContext getBundleContext() {
        Bundle bundle = FrameworkUtil.getBundle(YangToolsMapperHelper.class);
        return bundle != null ? bundle.getBundleContext() : null;
    }
}