8f0de4f73f8bdd2b7ae4b9760ed3b00e27eefc08
[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.eclipse.jdt.annotation.NonNull;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
52 /**
53  * YangToolsMapper is a specific Jackson mapper configuration for opendaylight yangtools serialization or deserialization of DataObject to/from JSON
54  * TODO ChoiceIn and Credentials deserialization only for LoginPasswordBuilder
55  */
56 public class YangToolsMapper2<T extends DataObject> extends ObjectMapper {
57
58         private final Logger LOG = LoggerFactory.getLogger(YangToolsMapper2.class);
59         private static final long serialVersionUID = 1L;
60         private static String ENTITY = "Entity";
61         private static String BUILDER = "Builder";
62
63         private @Nullable Class<T> clazz;
64         private @Nullable Class<? extends Builder<? extends T>> builderClazz;
65
66         private BundleContext context;
67
68         public <X extends T, B extends Builder<X>> YangToolsMapper2(Class<T> clazz, Class<B> builderClazz) throws ClassNotFoundException {
69                 super();
70                 configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
71                 setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
72                 setSerializationInclusion(Include.NON_NULL);
73                 setAnnotationIntrospector(new YangToolsBuilderAnnotationIntrospector());
74                 SimpleModule dateAndTimeSerializerModule = new SimpleModule();
75                 dateAndTimeSerializerModule.addSerializer(DateAndTime.class, new CustomDateAndTimeSerializer());
76                 registerModule(dateAndTimeSerializerModule );
77                 Bundle bundle = FrameworkUtil.getBundle(YangToolsMapper2.class);
78
79                 this.clazz = clazz;
80                 this.builderClazz = builderClazz != null ? builderClazz : getBuilderClass(getBuilderClassName(clazz)) ;
81                 context = bundle != null ? bundle.getBundleContext() : null;
82         }
83
84         public YangToolsMapper2() throws ClassNotFoundException {
85                 this(null, null);
86         }
87
88
89         @Override
90         public String writeValueAsString(Object value) throws JsonProcessingException {
91                 return super.writeValueAsString(value);
92         }
93         /**
94          * Get Builder object for yang tools interface.
95          * @param <T> yang-tools base datatype
96          * @param clazz class with interface.
97          * @return builder for interface or null if not existing
98          */
99         @SuppressWarnings("unchecked")
100         public @Nullable <T extends DataObject> Builder<T> getBuilder(Class<T> clazz) {
101                 try {
102                         //Class<?> clazzBuilder = getBuilderClass(getBuilderClassName(clazz));
103                         return (Builder<T>) builderClazz.newInstance();
104                 } catch (InstantiationException | IllegalAccessException e) {
105                         LOG.debug("Problem ", e);
106                         return null;
107                 }
108         }
109
110         /**
111          * Callback for handling mapping failures.
112          * @return
113          */
114         public int getMappingFailures() {
115                 return 0;
116         }
117
118         /**
119          * Provide mapping of string to attribute names, generated by yang-tools.
120          * "netconf-id" converted to "_netconfId"
121          * @param name with attribute name, not null or empty
122          * @return converted string or null if name was empty or null
123          */
124         public @Nullable static String toCamelCaseAttributeName(final String name) {
125                 if (name == null || name.isEmpty())
126                         return null;
127
128                 final StringBuilder ret = new StringBuilder(name.length());
129                 if (!name.startsWith("_"))
130                         ret.append('_');
131                 int start = 0;
132                 for (final String word : name.split("-")) {
133                         if (!word.isEmpty()) {
134                                 if (start++ == 0) {
135                                         ret.append(Character.toLowerCase(word.charAt(0)));
136                                 } else {
137                                         ret.append(Character.toUpperCase(word.charAt(0)));
138                                 }
139                                 ret.append(word.substring(1));
140                         }
141                 }
142                 return ret.toString();
143         }
144
145         /** Verify if builder is available
146          * @throws ClassNotFoundException **/
147         public Class<?> assertBuilderClass(Class<?> clazz) throws ClassNotFoundException {
148                 return getBuilderClass(getBuilderClassName(clazz));
149         }
150
151         // --- Private functions
152
153         /**
154          * Create name of builder class
155          * @param <T>
156          * @param clazz
157          * @return builders class name
158          * @throws ClassNotFoundException
159          */
160         private static String getBuilderClassName(Class<?> clazz) {
161                 return clazz.getName() + BUILDER;
162 //              String clazzName = clazz.getName();
163 //              if (clazzName.endsWith(ENTITY)) {
164 //                      return clazzName.replace(ENTITY, BUILDER);
165 //              } else {
166 //                      return clazzName + BUILDER;
167 //              }
168         }
169
170         /**
171          * Search builder in context
172          * @param name
173          * @return
174          * @throws ClassNotFoundException
175          */
176         @SuppressWarnings("unchecked")
177         private <X extends T, B extends Builder<X>> Class<B> getBuilderClass(String name) throws ClassNotFoundException {
178                 // Try to find in other bundles
179                 if (context != null) {
180                         //OSGi environment
181                         for (Bundle b : context.getBundles()) {
182                                 try {
183                                         return (Class<B>) b.loadClass(name);
184                                 } catch (ClassNotFoundException e) {
185                                         // No problem, this bundle doesn't have the class
186                                 }
187                         }
188                         throw new ClassNotFoundException("Can not find Class in OSGi context.");
189                 } else {
190                         return (Class<B>) Class.forName(name);
191                 }
192             // not found in any bundle
193         }
194
195         // --- Classes
196
197         /**
198          * Adapted Builder callbacks
199          */
200         private class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector {
201                 private static final long serialVersionUID = 1L;
202
203                 @Override
204                 public Class<?> findPOJOBuilder(AnnotatedClass ac) {
205
206                         if (ac.getRawType().equals(Credentials.class)) {
207                                 return org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder.class;
208
209                         } else if (ac.getRawType().equals(DateAndTime.class)) {
210                                 return DateAndTimeBuilder.class;
211
212                         } else if (ac.getRawType().equals(clazz)) {
213                                 return builderClazz;
214                         }
215
216                         if (ac.getRawType().isInterface()) {
217                                 String builder = getBuilderClassName(ac.getRawType());
218                                 try {
219                                         Class<?> innerBuilder = getBuilderClass(builder);
220                                         return innerBuilder;
221                                 } catch (ClassNotFoundException e) {
222                                         // No problem .. try next
223                                 }
224                         }
225                         return super.findPOJOBuilder(ac);
226                 }
227
228                 @Override
229                 public Value findPOJOBuilderConfig(AnnotatedClass ac) {
230                         if (ac.hasAnnotation(JsonPOJOBuilder.class)) {
231                                 return super.findPOJOBuilderConfig(ac);
232                         }
233                         return new JsonPOJOBuilder.Value("build", "set");
234                 }
235         }
236
237         public static class DateAndTimeBuilder{
238
239                 private final String _value;
240
241                 public DateAndTimeBuilder(String v) {
242                         this._value= v;
243                 }
244
245                 public DateAndTime build() {
246                         return new DateAndTime(_value);
247                 }
248
249         }
250         public static class CustomDateAndTimeSerializer extends StdSerializer<@NonNull DateAndTime>{
251
252                 private static final long serialVersionUID = 1L;
253
254                 public CustomDateAndTimeSerializer() {
255                         this(null);
256                 }
257                 protected CustomDateAndTimeSerializer(Class<DateAndTime> t) {
258                         super(t);
259                 }
260
261                 @Override
262                 public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
263                         gen.writeString(value.getValue());
264                 }
265
266         }
267 }