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 java.lang.reflect.Constructor;
 
  26 import java.lang.reflect.InvocationTargetException;
 
  27 import java.lang.reflect.Method;
 
  28 import java.time.Instant;
 
  29 import java.time.ZoneOffset;
 
  30 import java.time.ZonedDateTime;
 
  31 import java.time.format.DateTimeFormatter;
 
  32 import java.util.ArrayList;
 
  33 import java.util.Arrays;
 
  34 import java.util.List;
 
  35 import java.util.Optional;
 
  36 import java.util.concurrent.ConcurrentHashMap;
 
  37 import javax.annotation.Nullable;
 
  38 import org.opendaylight.mdsal.dom.api.DOMEvent;
 
  39 import org.opendaylight.mdsal.dom.api.DOMNotification;
 
  40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
 
  41 import org.opendaylight.yangtools.concepts.Builder;
 
  42 import org.opendaylight.yangtools.yang.binding.EventInstantAware;
 
  43 import org.opendaylight.yangtools.yang.binding.Notification;
 
  44 import org.osgi.framework.Bundle;
 
  45 import org.osgi.framework.BundleContext;
 
  46 import org.osgi.framework.FrameworkUtil;
 
  47 import org.slf4j.Logger;
 
  48 import org.slf4j.LoggerFactory;
 
  50 public class YangToolsMapperHelper {
 
  52     private static final Logger LOG = LoggerFactory.getLogger(YangToolsMapperHelper.class);
 
  53     private static final String TYPEOBJECT_INSTANCE_METHOD = "getDefaultInstance";
 
  54     private static final String BUILDER = "Builder";
 
  55     private static final DateTimeFormatter formatterOutput =
 
  56             DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.S'Z'").withZone(ZoneOffset.UTC);
 
  58     private static BundleContext context = getBundleContext();
 
  59     private static ConcurrentHashMap<String, Class<?>> cache = new ConcurrentHashMap<>();
 
  61     private YangToolsMapperHelper() {
 
  65     public static Class<?> findClass(String name) throws ClassNotFoundException {
 
  68         Class<?> res = cache.get(name);
 
  72         //Try first in actual bundle
 
  74             return loadClass(null, name);
 
  75         } catch (ClassNotFoundException e) {
 
  76             // No problem, this bundle doesn't have the class
 
  78         // Try to find in other bundles
 
  79         if (context != null) {
 
  81             for (Bundle b : context.getBundles()) {
 
  83                     return loadClass(b, name);
 
  84                 } catch (ClassNotFoundException e) {
 
  85                     // No problem, this bundle doesn't have the class
 
  89         // really not found in any bundle
 
  90         throw new ClassNotFoundException("Can not find class '" + name + "'");
 
  93     private static Class<?> loadClass(Bundle b, String name) throws ClassNotFoundException {
 
  94         Class<?> res = b == null ? Class.forName(name) : b.loadClass(name);
 
 100      * Verify if builder is available
 
 102      * @throws ClassNotFoundException
 
 104     public static Class<?> assertBuilderClass(Class<?> clazz) throws ClassNotFoundException {
 
 105         return getBuilderClass(getBuilderClassName(clazz));
 
 108     public static Class<?> getBuilderClass(String name) throws ClassNotFoundException {
 
 109         return findClass(name);
 
 112     public static Class<?> getBuilderClass(Class<?> clazz) throws ClassNotFoundException {
 
 113         return findClass(getBuilderClassName(clazz));
 
 117      * Create name of builder class
 
 121      * @return builders class name
 
 122      * @throws ClassNotFoundException
 
 124     public static String getBuilderClassName(Class<?> clazz) {
 
 125         return clazz.getName() + BUILDER;
 
 128     @SuppressWarnings("unchecked")
 
 129     public static <B extends Builder<?>> Class<B> findBuilderClass(DeserializationContext ctxt, Class<?> clazz)
 
 130             throws ClassNotFoundException {
 
 131         return (Class<B>) findClass(getBuilderClassName(clazz));
 
 134     public static <B extends Builder<?>> Optional<Class<B>> findBuilderClassOptional(DeserializationContext ctxt,
 
 137             return Optional.of(findBuilderClass(ctxt, clazz));
 
 138         } catch (ClassNotFoundException e) {
 
 139             return Optional.empty();
 
 143     public static boolean hasClassDeclaredMethod(Class<?> clazz, String name) {
 
 144         Method[] methods = clazz.getDeclaredMethods();
 
 145         for (Method m : methods) {
 
 146             if (m.getName().equals(name)) {
 
 153     @SuppressWarnings("unchecked")
 
 154     public static <T> Optional<T> getInstanceByConstructor(Class<?> clazz, String arg)
 
 155             throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
 
 156             NoSuchMethodException, SecurityException {
 
 157         List<Class<?>> ctypes = getConstructorParameterTypes(clazz, String.class);
 
 158         Optional<Object> oObj;
 
 159         for (Class<?> ctype : ctypes) {
 
 160             if (ctype.equals(String.class)) {
 
 161                 return Optional.of((T) clazz.getConstructor(ctype).newInstance(arg));
 
 162             } else if ((oObj = getDefaultInstance(ctype, arg)).isPresent()) {
 
 163                 return Optional.of((T) clazz.getConstructor(ctype).newInstance(oObj.get()));
 
 165                 // TODO: recursive instantiation down to string constructor or
 
 166                 // getDefaultInstance method
 
 167                 LOG.debug("Not implemented arg:'{}' class:'{}'", arg, clazz);
 
 170         return Optional.empty();
 
 173     @SuppressWarnings("unchecked")
 
 174     public static <T> Optional<T> getDefaultInstance(@Nullable Class<?> clazz, String arg) throws NoSuchMethodException,
 
 175             SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
 
 176         LOG.trace("arg:'{}' clazz '{}'", arg, clazz != null ? clazz.getName() : "null");
 
 178             Method[] methods = clazz.getDeclaredMethods();
 
 179             for (Method m : methods) {
 
 180                 //TODO Verify argument type to avoid exception
 
 181                 if (m.getName().equals(TYPEOBJECT_INSTANCE_METHOD)) {
 
 182                     Method method = clazz.getDeclaredMethod(TYPEOBJECT_INSTANCE_METHOD, String.class);
 
 183                     LOG.trace("Invoke {} available {}", TYPEOBJECT_INSTANCE_METHOD, method != null);
 
 184                     return Optional.of((T) method.invoke(null, arg));
 
 188         return Optional.empty();
 
 191     public static <T> Optional<T> getDefaultInstance(Optional<Class<T>> optionalClazz, String arg)
 
 192             throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
 
 193             InvocationTargetException {
 
 194         if (optionalClazz.isPresent()) {
 
 195             return getDefaultInstance(optionalClazz.get(), arg);
 
 197         return Optional.empty();
 
 200     public static List<Class<?>> getConstructorParameterTypes(Class<?> clazz, Class<?> prefer) {
 
 202         Constructor<?>[] constructors = clazz.getConstructors();
 
 203         List<Class<?>> res = new ArrayList<>();
 
 204         for (Constructor<?> c : constructors) {
 
 205             Class<?>[] ptypes = c.getParameterTypes();
 
 206             if (ptypes.length == 1) {
 
 210             if (prefer != null && ptypes.length == 1 && ptypes[0].equals(prefer)) {
 
 211                 return Arrays.asList(prefer);
 
 217     public static boolean implementsInterface(Class<?> clz, Class<?> ifToImplement) {
 
 218         if (clz.equals(ifToImplement)) {
 
 221         Class<?>[] ifs = clz.getInterfaces();
 
 222         for (Class<?> iff : ifs) {
 
 223             if (iff.equals(ifToImplement)) {
 
 227         return ifToImplement.isAssignableFrom(clz);
 
 231      * Provide mapping of string to attribute names, generated by yang-tools. "netconf-id" converted to "_netconfId"
 
 233      * @param name with attribute name, not null or empty
 
 234      * @return converted string or null if name was empty or null
 
 236     public @Nullable static String toCamelCaseAttributeName(final String name) {
 
 237         if (name == null || name.isEmpty())
 
 240         final StringBuilder ret = new StringBuilder(name.length());
 
 241         if (!name.startsWith("_"))
 
 243         ret.append(toCamelCase(name));
 
 244         return ret.toString();
 
 247     public static String toCamelCase(final String name) {
 
 249         final StringBuilder ret = new StringBuilder(name.length());
 
 250         for (final String word : name.split("-")) {
 
 251             if (!word.isEmpty()) {
 
 253                     ret.append(Character.toLowerCase(word.charAt(0)));
 
 255                     ret.append(Character.toUpperCase(word.charAt(0)));
 
 257                 ret.append(word.substring(1));
 
 260         return ret.toString();
 
 263     public static String toCamelCaseClassName(final String name) {
 
 264         final String clsName = toCamelCase(name);
 
 265         return clsName.substring(0, 1).toUpperCase() + clsName.substring(1);
 
 268     private static BundleContext getBundleContext() {
 
 269         Bundle bundle = FrameworkUtil.getBundle(YangToolsMapperHelper.class);
 
 270         return bundle != null ? bundle.getBundleContext() : null;
 
 273     public static boolean hasTime(Notification notification) {
 
 274         return notification instanceof EventInstantAware;
 
 277     public static boolean hasTime(DOMNotification notification) {
 
 278         return notification instanceof DOMEvent;
 
 281     public static DateAndTime getTime(Notification notification, Instant defaultValue) {
 
 283         if (hasTime(notification)) { // If notification class extends/implements the EventInstantAware
 
 284             time = ((EventInstantAware) notification).eventInstant();
 
 285             LOG.debug("Event time {}", time);
 
 288             LOG.debug("Defaulting to actual time of processing the notification - {}", time);
 
 290         return DateAndTime.getDefaultInstance(ZonedDateTime.ofInstant(time, ZoneOffset.UTC).format(formatterOutput));
 
 293     public static DateAndTime getTime(DOMNotification notification, Instant defaultValue) {
 
 295         if (hasTime(notification)) { // If notification class extends/implements the EventInstantAware
 
 296             time = ((DOMEvent) notification).getEventInstant();
 
 297             LOG.debug("Event time {}", time);
 
 300             LOG.debug("Defaulting to actual time of processing the notification - {}", time);
 
 302         return DateAndTime.getDefaultInstance(ZonedDateTime.ofInstant(time, ZoneOffset.UTC).format(formatterOutput));