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.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
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
55 public class YangToolsMapper extends ObjectMapper {
57 private final Logger LOG = LoggerFactory.getLogger(YangToolsMapper.class);
58 private static final long serialVersionUID = 1L;
59 private static BundleContext context;
61 public YangToolsMapper() {
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;
75 public String writeValueAsString(Object value) throws JsonProcessingException {
76 // TODO Auto-generated method stub
77 return super.writeValueAsString(value);
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
85 @SuppressWarnings("unchecked")
86 public @Nullable <T extends DataObject> Builder<T> getBuilder(Class<T> clazz) {
87 String builder = clazz.getName() + "Builder";
89 Class<?> clazzBuilder = findClass(builder);
90 return (Builder<T>) clazzBuilder.newInstance();
91 } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
92 LOG.debug("Problem ", e);
98 * Callback for handling mapping failures.
101 public int getMappingFailures() {
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
111 public @Nullable static String toCamelCaseAttributeName(final String name) {
112 if (name == null || name.isEmpty())
115 final StringBuilder ret = new StringBuilder(name.length());
116 if (!name.startsWith("_"))
119 for (final String word : name.split("-")) {
120 if (!word.isEmpty()) {
122 ret.append(Character.toLowerCase(word.charAt(0)));
124 ret.append(Character.toUpperCase(word.charAt(0)));
126 ret.append(word.substring(1));
129 return ret.toString();
133 * Adapted Builder callbacks
135 private static class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector {
136 private static final long serialVersionUID = 1L;
139 public Class<?> findPOJOBuilder(AnnotatedClass ac) {
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()));
148 else if(ac.getRawType().equals(DateAndTime.class)) {
149 builder = DateAndTimeBuilder.class.getName();
153 if (ac.getRawType().isInterface()) {
154 builder = ac.getName()+"Builder";
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);
165 } catch( ClassNotFoundException e ) {
166 // No problem .. try next
168 return super.findPOJOBuilder(ac);
172 public Value findPOJOBuilderConfig(AnnotatedClass ac) {
173 if (ac.hasAnnotation(JsonPOJOBuilder.class)) {
174 return super.findPOJOBuilderConfig(ac);
176 return new JsonPOJOBuilder.Value("build", "set");
180 private static Class<?> findClass(String name) throws ClassNotFoundException {
181 // Try to find in other bundles
182 if (context != null) {
184 for (Bundle b : context.getBundles()) {
186 return b.loadClass(name);
187 } catch (ClassNotFoundException e) {
188 // No problem, this bundle doesn't have the class
191 throw new ClassNotFoundException("Can not find Class in OSGi context.");
193 return Class.forName(name);
195 // not found in any bundle
197 public static class DateAndTimeBuilder{
199 private final String _value;
201 public DateAndTimeBuilder(String v) {
205 public DateAndTime build() {
206 return new DateAndTime(_value);
210 public static class CustomDateAndTimeSerializer extends StdSerializer<DateAndTime>{
215 private static final long serialVersionUID = 1L;
217 public CustomDateAndTimeSerializer() {
220 protected CustomDateAndTimeSerializer(Class<DateAndTime> t) {
225 public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
226 gen.writeString(value.getValue());