0ee76b074ffa54eaecf470e9c73d7942aa9a974e
[ccsdk/features.git] /
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.yangtools;
19
20 import java.io.IOException;
21 import javax.annotation.Nullable;
22
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
24 import org.opendaylight.yangtools.concepts.Builder;
25 import org.opendaylight.yangtools.yang.binding.DataObject;
26 import org.osgi.framework.Bundle;
27 import org.osgi.framework.BundleContext;
28 import org.osgi.framework.FrameworkUtil;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import com.fasterxml.jackson.annotation.JsonInclude.Include;
33 import com.fasterxml.jackson.core.JsonGenerator;
34 import com.fasterxml.jackson.core.JsonProcessingException;
35 import com.fasterxml.jackson.databind.DeserializationFeature;
36 import com.fasterxml.jackson.databind.ObjectMapper;
37 import com.fasterxml.jackson.databind.PropertyNamingStrategy;
38 import com.fasterxml.jackson.databind.SerializerProvider;
39 import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
40 import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder.Value;
41 import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
42 import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
43 import com.fasterxml.jackson.databind.module.SimpleModule;
44 import com.fasterxml.jackson.databind.ser.std.StdSerializer;
45
46 import org.eclipse.jdt.annotation.NonNull;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
48 /**
49  * YangToolsMapper is a specific Jackson mapper configuration for opendaylight yangtools serialization or deserialization of DataObject to/from JSON
50  * TODO ChoiceIn and Credentials deserialization only for LoginPasswordBuilder
51  */
52 public class YangToolsMapper2<T extends DataObject> extends ObjectMapper {
53
54         private final Logger LOG = LoggerFactory.getLogger(YangToolsMapper2.class);
55         private static final long serialVersionUID = 1L;
56         private static String ENTITY = "Entity";
57         private static String BUILDER = "Builder";
58
59         private @Nullable Class<T> clazz;
60         private @Nullable Class<? extends Builder<? extends T>> builderClazz;
61
62         private BundleContext context;
63
64         public <X extends T, B extends Builder<X>> YangToolsMapper2(Class<T> clazz, Class<B> builderClazz) throws ClassNotFoundException {
65                 super();
66                 configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
67                 setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
68                 setSerializationInclusion(Include.NON_NULL);
69                 setAnnotationIntrospector(new YangToolsBuilderAnnotationIntrospector());
70                 SimpleModule dateAndTimeSerializerModule = new SimpleModule();
71                 dateAndTimeSerializerModule.addSerializer(DateAndTime.class, new CustomDateAndTimeSerializer());
72                 registerModule(dateAndTimeSerializerModule );
73                 Bundle bundle = FrameworkUtil.getBundle(YangToolsMapper2.class);
74
75                 this.clazz = clazz;
76                 this.builderClazz = builderClazz != null ? builderClazz : getBuilderClass(getBuilderClassName(clazz)) ;
77                 context = bundle != null ? bundle.getBundleContext() : null;
78         }
79
80         public YangToolsMapper2() throws ClassNotFoundException {
81                 this(null, null);
82         }
83
84
85         @Override
86         public String writeValueAsString(Object value) throws JsonProcessingException {
87                 return super.writeValueAsString(value);
88         }
89         /**
90          * Get Builder object for yang tools interface.
91          * @param <T> yang-tools base datatype
92          * @param clazz class with interface.
93          * @return builder for interface or null if not existing
94          */
95         @SuppressWarnings("unchecked")
96         public @Nullable <T extends DataObject> Builder<T> getBuilder(Class<T> clazz) {
97                 try {
98                         //Class<?> clazzBuilder = getBuilderClass(getBuilderClassName(clazz));
99                         return (Builder<T>) builderClazz.newInstance();
100                 } catch (InstantiationException | IllegalAccessException e) {
101                         LOG.debug("Problem ", e);
102                         return null;
103                 }
104         }
105
106         /**
107          * Callback for handling mapping failures.
108          * @return
109          */
110         public int getMappingFailures() {
111                 return 0;
112         }
113
114         /**
115          * Provide mapping of string to attribute names, generated by yang-tools.
116          * "netconf-id" converted to "_netconfId"
117          * @param name with attribute name, not null or empty
118          * @return converted string or null if name was empty or null
119          */
120         public @Nullable static String toCamelCaseAttributeName(final String name) {
121                 if (name == null || name.isEmpty())
122                         return null;
123
124                 final StringBuilder ret = new StringBuilder(name.length());
125                 if (!name.startsWith("_"))
126                         ret.append('_');
127                 int start = 0;
128                 for (final String word : name.split("-")) {
129                         if (!word.isEmpty()) {
130                                 if (start++ == 0) {
131                                         ret.append(Character.toLowerCase(word.charAt(0)));
132                                 } else {
133                                         ret.append(Character.toUpperCase(word.charAt(0)));
134                                 }
135                                 ret.append(word.substring(1));
136                         }
137                 }
138                 return ret.toString();
139         }
140
141         /** Verify if builder is available
142          * @throws ClassNotFoundException **/
143         public Class<?> assertBuilderClass(Class<?> clazz) throws ClassNotFoundException {
144                 return getBuilderClass(getBuilderClassName(clazz));
145         }
146
147         // --- Private functions
148
149         /**
150          * Create name of builder class
151          * @param <T>
152          * @param clazz
153          * @return builders class name
154          * @throws ClassNotFoundException
155          */
156         private static String getBuilderClassName(Class<?> clazz) {
157                 return clazz.getName() + BUILDER;
158 //              String clazzName = clazz.getName();
159 //              if (clazzName.endsWith(ENTITY)) {
160 //                      return clazzName.replace(ENTITY, BUILDER);
161 //              } else {
162 //                      return clazzName + BUILDER;
163 //              }
164         }
165
166         /**
167          * Search builder in context
168          * @param name
169          * @return
170          * @throws ClassNotFoundException
171          */
172         @SuppressWarnings("unchecked")
173         private <X extends T, B extends Builder<X>> Class<B> getBuilderClass(String name) throws ClassNotFoundException {
174                 // Try to find in other bundles
175                 if (context != null) {
176                         //OSGi environment
177                         for (Bundle b : context.getBundles()) {
178                                 try {
179                                         return (Class<B>) b.loadClass(name);
180                                 } catch (ClassNotFoundException e) {
181                                         // No problem, this bundle doesn't have the class
182                                 }
183                         }
184                         throw new ClassNotFoundException("Can not find Class in OSGi context.");
185                 } else {
186                         return (Class<B>) Class.forName(name);
187                 }
188             // not found in any bundle
189         }
190
191         // --- Classes
192
193         /**
194          * Adapted Builder callbacks
195          */
196         private class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector {
197                 private static final long serialVersionUID = 1L;
198
199                 @Override
200                 public Class<?> findPOJOBuilder(AnnotatedClass ac) {
201
202                         if (ac.getRawType().equals(Credentials.class)) {
203                                 return org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder.class;
204
205                         } else if (ac.getRawType().equals(DateAndTime.class)) {
206                                 return DateAndTimeBuilder.class;
207
208                         } else if (ac.getRawType().equals(clazz)) {
209                                 return builderClazz;
210                         }
211
212                         if (ac.getRawType().isInterface()) {
213                                 String builder = getBuilderClassName(ac.getRawType());
214                                 try {
215                                         Class<?> innerBuilder = getBuilderClass(builder);
216                                         return innerBuilder;
217                                 } catch (ClassNotFoundException e) {
218                                         // No problem .. try next
219                                 }
220                         }
221                         return super.findPOJOBuilder(ac);
222                 }
223
224                 @Override
225                 public Value findPOJOBuilderConfig(AnnotatedClass ac) {
226                         if (ac.hasAnnotation(JsonPOJOBuilder.class)) {
227                                 return super.findPOJOBuilderConfig(ac);
228                         }
229                         return new JsonPOJOBuilder.Value("build", "set");
230                 }
231         }
232
233         public static class DateAndTimeBuilder{
234
235                 private final String _value;
236
237                 public DateAndTimeBuilder(String v) {
238                         this._value= v;
239                 }
240
241                 public DateAndTime build() {
242                         return new DateAndTime(_value);
243                 }
244
245         }
246         public static class CustomDateAndTimeSerializer extends StdSerializer<@NonNull DateAndTime>{
247
248                 private static final long serialVersionUID = 1L;
249
250                 public CustomDateAndTimeSerializer() {
251                         this(null);
252                 }
253                 protected CustomDateAndTimeSerializer(Class<DateAndTime> t) {
254                         super(t);
255                 }
256
257                 @Override
258                 public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
259                         gen.writeString(value.getValue());
260                 }
261
262         }
263 }