2 * ============LICENSE_START=======================================================
3 * ONAP : ccsdk features
4 * ================================================================================
5 * Copyright (C) 2019 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.dataprovider.yangtools;
24 import java.io.IOException;
25 import javax.annotation.Nullable;
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;
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;
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;
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
56 public class YangToolsMapper2<T extends DataObject> extends ObjectMapper {
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";
63 private @Nullable Class<T> clazz;
64 private @Nullable Class<? extends Builder<? extends T>> builderClazz;
66 private BundleContext context;
68 public <X extends T, B extends Builder<X>> YangToolsMapper2(Class<T> clazz, Class<B> builderClazz) throws ClassNotFoundException {
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);
80 this.builderClazz = builderClazz != null ? builderClazz : getBuilderClass(getBuilderClassName(clazz)) ;
81 context = bundle != null ? bundle.getBundleContext() : null;
84 public YangToolsMapper2() throws ClassNotFoundException {
90 public String writeValueAsString(Object value) throws JsonProcessingException {
91 return super.writeValueAsString(value);
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
99 @SuppressWarnings("unchecked")
100 public @Nullable <T extends DataObject> Builder<T> getBuilder(Class<T> clazz) {
102 //Class<?> clazzBuilder = getBuilderClass(getBuilderClassName(clazz));
103 return (Builder<T>) builderClazz.newInstance();
104 } catch (InstantiationException | IllegalAccessException e) {
105 LOG.debug("Problem ", e);
111 * Callback for handling mapping failures.
114 public int getMappingFailures() {
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
124 public @Nullable static String toCamelCaseAttributeName(final String name) {
125 if (name == null || name.isEmpty())
128 final StringBuilder ret = new StringBuilder(name.length());
129 if (!name.startsWith("_"))
132 for (final String word : name.split("-")) {
133 if (!word.isEmpty()) {
135 ret.append(Character.toLowerCase(word.charAt(0)));
137 ret.append(Character.toUpperCase(word.charAt(0)));
139 ret.append(word.substring(1));
142 return ret.toString();
145 /** Verify if builder is available
146 * @throws ClassNotFoundException **/
147 public Class<?> assertBuilderClass(Class<?> clazz) throws ClassNotFoundException {
148 return getBuilderClass(getBuilderClassName(clazz));
151 // --- Private functions
154 * Create name of builder class
157 * @return builders class name
158 * @throws ClassNotFoundException
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);
166 // return clazzName + BUILDER;
171 * Search builder in context
174 * @throws ClassNotFoundException
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) {
181 for (Bundle b : context.getBundles()) {
183 return (Class<B>) b.loadClass(name);
184 } catch (ClassNotFoundException e) {
185 // No problem, this bundle doesn't have the class
188 throw new ClassNotFoundException("Can not find Class in OSGi context.");
190 return (Class<B>) Class.forName(name);
192 // not found in any bundle
198 * Adapted Builder callbacks
200 private class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector {
201 private static final long serialVersionUID = 1L;
204 public Class<?> findPOJOBuilder(AnnotatedClass ac) {
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;
209 } else if (ac.getRawType().equals(DateAndTime.class)) {
210 return DateAndTimeBuilder.class;
212 } else if (ac.getRawType().equals(clazz)) {
216 if (ac.getRawType().isInterface()) {
217 String builder = getBuilderClassName(ac.getRawType());
219 Class<?> innerBuilder = getBuilderClass(builder);
221 } catch (ClassNotFoundException e) {
222 // No problem .. try next
225 return super.findPOJOBuilder(ac);
229 public Value findPOJOBuilderConfig(AnnotatedClass ac) {
230 if (ac.hasAnnotation(JsonPOJOBuilder.class)) {
231 return super.findPOJOBuilderConfig(ac);
233 return new JsonPOJOBuilder.Value("build", "set");
237 public static class DateAndTimeBuilder{
239 private final String _value;
241 public DateAndTimeBuilder(String v) {
245 public DateAndTime build() {
246 return new DateAndTime(_value);
250 public static class CustomDateAndTimeSerializer extends StdSerializer<@NonNull DateAndTime>{
252 private static final long serialVersionUID = 1L;
254 public CustomDateAndTimeSerializer() {
257 protected CustomDateAndTimeSerializer(Class<DateAndTime> t) {
262 public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
263 gen.writeString(value.getValue());