768e6683becafc32a9d731dfd46bba46f328f04f
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
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
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.yangtools;
23
24 import java.io.IOException;
25 import javax.annotation.Nullable;
26
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
28 import org.opendaylight.yangtools.concepts.Builder;
29 import org.opendaylight.yangtools.yang.binding.DataObject;
30 import org.osgi.framework.Bundle;
31 import org.osgi.framework.BundleContext;
32 import org.osgi.framework.FrameworkUtil;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import com.fasterxml.jackson.annotation.JsonInclude.Include;
37 import com.fasterxml.jackson.core.JsonGenerator;
38 import com.fasterxml.jackson.core.JsonProcessingException;
39 import com.fasterxml.jackson.databind.DeserializationFeature;
40 import com.fasterxml.jackson.databind.ObjectMapper;
41 import com.fasterxml.jackson.databind.PropertyNamingStrategy;
42 import com.fasterxml.jackson.databind.SerializerProvider;
43 import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
44 import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder.Value;
45 import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
46 import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
47 import com.fasterxml.jackson.databind.module.SimpleModule;
48 import com.fasterxml.jackson.databind.ser.std.StdSerializer;
49
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
51 /**
52  * YangToolsMapper is a specific Jackson mapper configuration for opendaylight yangtools serialization or deserialization of DataObject to/from JSON
53  * TODO ChoiceIn and Credentials deserialization only for LoginPasswordBuilder
54  */
55 public class YangToolsMapper extends ObjectMapper {
56
57         private final Logger LOG = LoggerFactory.getLogger(YangToolsMapper.class);
58         private static final long serialVersionUID = 1L;
59         private static BundleContext context;
60
61         public YangToolsMapper() {
62                 super();
63                 configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
64                 setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
65                 setSerializationInclusion(Include.NON_NULL);
66                 setAnnotationIntrospector(new YangToolsBuilderAnnotationIntrospector());
67                 SimpleModule dateAndTimeSerializerModule = new SimpleModule();
68                 dateAndTimeSerializerModule.addSerializer(DateAndTime.class,new CustomDateAndTimeSerializer());
69                 registerModule(dateAndTimeSerializerModule );
70                 Bundle bundle = FrameworkUtil.getBundle(YangToolsMapper.class);
71                 context = bundle != null ? bundle.getBundleContext() : null;
72         }
73
74         @Override
75         public String writeValueAsString(Object value) throws JsonProcessingException {
76                 // TODO Auto-generated method stub
77                 return super.writeValueAsString(value);
78         }
79         /**
80          * Get Builder object for yang tools interface.
81          * @param <T> yang-tools base datatype
82          * @param clazz class with interface.
83          * @return builder for interface or null if not existing
84          */
85         @SuppressWarnings("unchecked")
86         public @Nullable <T extends DataObject> Builder<T> getBuilder(Class<T> clazz) {
87                 String builder = clazz.getName() + "Builder";
88                 try {
89                         Class<?> clazzBuilder = findClass(builder);
90                         return (Builder<T>) clazzBuilder.newInstance();
91                 } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
92                         LOG.debug("Problem ", e);
93                         return null;
94                 }
95         }
96
97         /**
98          * Callback for handling mapping failures.
99          * @return
100          */
101         public int getMappingFailures() {
102                 return 0;
103         }
104
105         /**
106          * Provide mapping of string to attribute names, generated by yang-tools.
107          * "netconf-id" converted to "_netconfId"
108          * @param name with attribute name, not null or empty
109          * @return converted string or null if name was empty or null
110          */
111         public @Nullable static String toCamelCaseAttributeName(final String name) {
112                 if (name == null || name.isEmpty())
113                         return null;
114
115                 final StringBuilder ret = new StringBuilder(name.length());
116                 if (!name.startsWith("_"))
117                         ret.append('_');
118                 int start = 0;
119                 for (final String word : name.split("-")) {
120                         if (!word.isEmpty()) {
121                                 if (start++ == 0) {
122                                         ret.append(Character.toLowerCase(word.charAt(0)));
123                                 } else {
124                                         ret.append(Character.toUpperCase(word.charAt(0)));
125                                 }
126                                 ret.append(word.substring(1));
127                         }
128                 }
129                 return ret.toString();
130         }
131
132         /**
133          * Adapted Builder callbacks
134          */
135         private static class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector {
136                 private static final long serialVersionUID = 1L;
137
138                 @Override
139         public Class<?> findPOJOBuilder(AnnotatedClass ac) {
140                         try {
141                         String builder = null;
142                         if (ac.getRawType().equals(Credentials.class)) {
143                                 builder = "org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder";
144                                 //System.out.println(DataContainer.class.isAssignableFrom(ac.getRawType()));
145                                 //System.out.println(ChoiceIn.class.isAssignableFrom(ac.getRawType()));
146
147                         } 
148                         else if(ac.getRawType().equals(DateAndTime.class)) {
149                                 builder = DateAndTimeBuilder.class.getName();
150                         }
151                         
152                         else {
153                                 if (ac.getRawType().isInterface())      {
154                                         builder = ac.getName()+"Builder";
155                                 }
156                         }
157                         if (builder != null) {
158                                 //System.out.println("XX1: "+ac.getRawType());
159                                 //System.out.println("XX2: "+builder);
160                                 //Class<?> innerBuilder = Class.forName(builder);
161                                 Class<?> innerBuilder = findClass(builder);
162                             //System.out.println("Builder found: "+ innerBuilder);
163                             return innerBuilder;
164                         }
165                 } catch( ClassNotFoundException e ) {
166                     // No problem .. try next
167                 }
168            return super.findPOJOBuilder(ac);
169         }
170
171                 @Override
172                 public Value findPOJOBuilderConfig(AnnotatedClass ac) {
173                         if (ac.hasAnnotation(JsonPOJOBuilder.class)) {
174                                 return super.findPOJOBuilderConfig(ac);
175                         }
176                         return new JsonPOJOBuilder.Value("build", "set");
177                 }
178         }
179
180         private static Class<?> findClass(String name) throws ClassNotFoundException {
181                 // Try to find in other bundles
182                 if (context != null) {
183                         //OSGi environment
184                         for (Bundle b : context.getBundles()) {
185                                 try {
186                                         return b.loadClass(name);
187                                 } catch (ClassNotFoundException e) {
188                                         // No problem, this bundle doesn't have the class
189                                 }
190                         }
191                         throw new ClassNotFoundException("Can not find Class in OSGi context.");
192                 } else {
193                         return Class.forName(name);
194                 }
195             // not found in any bundle
196         }
197         public static class DateAndTimeBuilder{
198                 
199                 private final String _value;
200         
201                 public DateAndTimeBuilder(String v) {
202                         this._value= v;
203                 }
204                 
205                 public DateAndTime build() {
206                         return new DateAndTime(_value);
207                 }
208                 
209         }
210         public static class CustomDateAndTimeSerializer extends StdSerializer<DateAndTime>{
211
212                 /**
213                  * 
214                  */
215                 private static final long serialVersionUID = 1L;
216
217                 public CustomDateAndTimeSerializer() {
218                         this(null);
219                 }
220                 protected CustomDateAndTimeSerializer(Class<DateAndTime> t) {
221                         super(t);
222                 }
223
224                 @Override
225                 public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
226                         gen.writeString(value.getValue());
227                 }
228                 
229         }
230 }