2 * ============LICENSE_START=======================================================
3 * ONAP : ccsdk features
4 * ================================================================================
5 * Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.features.sdnr.wt.yang.mapper;
24 import com.fasterxml.jackson.databind.DeserializationContext;
25 import com.google.common.collect.Maps;
27 import java.lang.reflect.Constructor;
28 import java.lang.reflect.Field;
29 import java.lang.reflect.InvocationTargetException;
30 import java.lang.reflect.Method;
31 import java.time.Instant;
32 import java.time.ZoneOffset;
33 import java.time.ZonedDateTime;
34 import java.time.format.DateTimeFormatter;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.List;
39 import java.util.Optional;
40 import java.util.concurrent.ConcurrentHashMap;
41 import javax.annotation.Nullable;
43 import org.opendaylight.mdsal.dom.api.DOMEvent;
44 import org.opendaylight.mdsal.dom.api.DOMNotification;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
47 import org.opendaylight.yangtools.yang.binding.*;
48 import org.osgi.framework.Bundle;
49 import org.osgi.framework.BundleContext;
50 import org.osgi.framework.FrameworkUtil;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public class YangToolsMapperHelper {
56 private static final Logger LOG = LoggerFactory.getLogger(YangToolsMapperHelper.class);
57 private static final String TYPEOBJECT_INSTANCE_METHOD = "getDefaultInstance";
58 private static final String BUILDER = "Builder";
59 private static final DateTimeFormatter formatterOutput =
60 DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.S'Z'").withZone(ZoneOffset.UTC);
62 private static BundleContext context = getBundleContext();
63 private static ConcurrentHashMap<String, Class<?>> cache = new ConcurrentHashMap<>();
65 private YangToolsMapperHelper() {
69 public static Class<?> findClass(String name) throws ClassNotFoundException {
72 Class<?> res = cache.get(name);
76 //Try first in actual bundle
78 return loadClass(null, name);
79 } catch (ClassNotFoundException e) {
80 // No problem, this bundle doesn't have the class
82 // Try to find in other bundles
83 if (context != null) {
85 for (Bundle b : context.getBundles()) {
87 return loadClass(b, name);
88 } catch (ClassNotFoundException e) {
89 // No problem, this bundle doesn't have the class
93 // really not found in any bundle
94 throw new ClassNotFoundException("Can not find class '" + name + "'");
97 private static Class<?> loadClass(Bundle b, String name) throws ClassNotFoundException {
98 Class<?> res = b == null ? Class.forName(name) : b.loadClass(name);
104 * Verify if builder is available
106 * @throws ClassNotFoundException
108 public static Class<?> assertBuilderClass(Class<?> clazz) throws ClassNotFoundException {
109 return getBuilderClass(getBuilderClassName(clazz));
112 public static Class<?> getBuilderClass(String name) throws ClassNotFoundException {
113 return findClass(name);
116 public static Class<?> getBuilderClass(Class<?> clazz) throws ClassNotFoundException {
117 return findClass(getBuilderClassName(clazz));
121 * Create name of builder class
125 * @return builders class name
126 * @throws ClassNotFoundException
128 public static String getBuilderClassName(Class<?> clazz) {
129 return clazz.getName() + BUILDER;
132 @SuppressWarnings("unchecked")
133 public static Class<?> findBuilderClass(DeserializationContext ctxt, Class<?> clazz)
134 throws ClassNotFoundException {
135 return findClass(getBuilderClassName(clazz));
138 public static Optional<Class<?>> findBuilderClassOptional(DeserializationContext ctxt,
141 return Optional.of(findBuilderClass(ctxt, clazz));
142 } catch (ClassNotFoundException e) {
143 return Optional.empty();
147 public static <T extends BaseIdentity, S extends T> S getIdentityValueFromClass(Class<S> clazz) {
149 Field valueField = clazz.getDeclaredField("VALUE");
150 return (S) valueField.get(clazz);
151 } catch (NoSuchFieldException | IllegalAccessException ignore) {
156 public static boolean hasClassDeclaredMethod(Class<?> clazz, String name) {
157 Method[] methods = clazz.getDeclaredMethods();
158 for (Method m : methods) {
159 if (m.getName().equals(name)) {
166 @SuppressWarnings("unchecked")
167 public static <T> Optional<T> getInstanceByConstructor(Class<?> clazz, String arg)
168 throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
169 NoSuchMethodException, SecurityException {
170 List<Class<?>> ctypes = getConstructorParameterTypes(clazz, String.class);
171 Optional<Object> oObj;
172 for (Class<?> ctype : ctypes) {
173 if (ctype.equals(String.class)) {
174 return Optional.of((T) clazz.getConstructor(ctype).newInstance(arg));
175 } else if ((oObj = getDefaultInstance(ctype, arg)).isPresent()) {
176 return Optional.of((T) clazz.getConstructor(ctype).newInstance(oObj.get()));
178 // TODO: recursive instantiation down to string constructor or
179 // getDefaultInstance method
180 LOG.debug("Not implemented arg:'{}' class:'{}'", arg, clazz);
183 return Optional.empty();
186 @SuppressWarnings("unchecked")
187 public static <T> Optional<T> getDefaultInstance(@Nullable Class<?> clazz, String arg) throws NoSuchMethodException,
188 SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
189 LOG.trace("arg:'{}' clazz '{}'", arg, clazz != null ? clazz.getName() : "null");
191 Method[] methods = clazz.getDeclaredMethods();
192 for (Method m : methods) {
193 //TODO Verify argument type to avoid exception
194 if (m.getName().equals(TYPEOBJECT_INSTANCE_METHOD)) {
195 Method method = clazz.getDeclaredMethod(TYPEOBJECT_INSTANCE_METHOD, String.class);
196 LOG.trace("Invoke {} available {}", TYPEOBJECT_INSTANCE_METHOD, method != null);
197 return Optional.of((T) method.invoke(null, arg));
201 return Optional.empty();
204 public static <T> Optional<T> getDefaultInstance(Optional<Class<T>> optionalClazz, String arg)
205 throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
206 InvocationTargetException {
207 if (optionalClazz.isPresent()) {
208 return getDefaultInstance(optionalClazz.get(), arg);
210 return Optional.empty();
213 public static List<Class<?>> getConstructorParameterTypes(Class<?> clazz, Class<?> prefer) {
215 Constructor<?>[] constructors = clazz.getConstructors();
216 List<Class<?>> res = new ArrayList<>();
217 for (Constructor<?> c : constructors) {
218 Class<?>[] ptypes = c.getParameterTypes();
219 if (ptypes.length == 1) {
223 if (prefer != null && ptypes.length == 1 && ptypes[0].equals(prefer)) {
224 return Arrays.asList(prefer);
230 public static boolean implementsInterface(Class<?> clz, Class<?> ifToImplement) {
231 if (clz.equals(ifToImplement)) {
234 Class<?>[] ifs = clz.getInterfaces();
235 for (Class<?> iff : ifs) {
236 if (iff.equals(ifToImplement)) {
240 return ifToImplement.isAssignableFrom(clz);
244 * Provide mapping of string to attribute names, generated by yang-tools. "netconf-id" converted to "_netconfId"
246 * @param name with attribute name, not null or empty
247 * @return converted string or null if name was empty or null
250 static String toCamelCaseAttributeName(final String name) {
251 if (name == null || name.isEmpty())
254 final StringBuilder ret = new StringBuilder(name.length());
255 if (!name.startsWith("_"))
257 ret.append(toCamelCase(name));
258 return ret.toString();
261 public static String toCamelCase(final String name) {
263 final StringBuilder ret = new StringBuilder(name.length());
264 for (final String word : name.split("-")) {
265 if (!word.isEmpty()) {
267 ret.append(Character.toLowerCase(word.charAt(0)));
269 ret.append(Character.toUpperCase(word.charAt(0)));
271 ret.append(word.substring(1));
274 return ret.toString();
277 public static String toCamelCaseClassName(final String name) {
278 final String clsName = toCamelCase(name);
279 return clsName.substring(0, 1).toUpperCase() + clsName.substring(1);
282 private static BundleContext getBundleContext() {
283 Bundle bundle = FrameworkUtil.getBundle(YangToolsMapperHelper.class);
284 return bundle != null ? bundle.getBundleContext() : null;
287 public static boolean hasTime(Notification notification) {
288 return notification instanceof EventInstantAware;
291 public static boolean hasTime(DOMNotification notification) {
292 return notification instanceof DOMEvent;
295 public static DateAndTime getTime(Notification notification, Instant defaultValue) {
297 if (hasTime(notification)) { // If notification class extends/implements the EventInstantAware
298 time = ((EventInstantAware) notification).eventInstant();
299 LOG.debug("Event time {}", time);
302 LOG.debug("Defaulting to actual time of processing the notification - {}", time);
304 return DateAndTime.getDefaultInstance(ZonedDateTime.ofInstant(time, ZoneOffset.UTC).format(formatterOutput));
307 public static DateAndTime getTime(DOMNotification notification, Instant defaultValue) {
309 if (hasTime(notification)) { // If notification class extends/implements the EventInstantAware
310 time = ((DOMEvent) notification).getEventInstant();
311 LOG.debug("Event time {}", time);
314 LOG.debug("Defaulting to actual time of processing the notification - {}", time);
316 return DateAndTime.getDefaultInstance(ZonedDateTime.ofInstant(time, ZoneOffset.UTC).format(formatterOutput));
320 public static <K extends Key<V>, V extends KeyAware<K>> Map<K, V> toMap(List<V> list) {
321 return list == null || list.isEmpty() ? null : Maps.uniqueIndex(list, KeyAware::key);
324 @SuppressWarnings("unchecked")
325 public static <S, T> T callBuild(S builder)
326 throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
327 InvocationTargetException {
328 Method method = builder.getClass().getMethod("build");
329 return (T) method.invoke(builder);