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
10 * http://www.apache.org/licenses/LICENSE-2.0
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
16 * ============LICENSE_END==========================================================================
17 ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.yangtools;
20 import java.io.IOException;
21 import javax.annotation.Nullable;
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;
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;
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;
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
52 public class YangToolsMapper2<T extends DataObject> extends ObjectMapper {
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";
59 private @Nullable Class<T> clazz;
60 private @Nullable Class<? extends Builder<? extends T>> builderClazz;
62 private BundleContext context;
64 public <X extends T, B extends Builder<X>> YangToolsMapper2(Class<T> clazz, Class<B> builderClazz) throws ClassNotFoundException {
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);
76 this.builderClazz = builderClazz != null ? builderClazz : getBuilderClass(getBuilderClassName(clazz)) ;
77 context = bundle != null ? bundle.getBundleContext() : null;
80 public YangToolsMapper2() throws ClassNotFoundException {
86 public String writeValueAsString(Object value) throws JsonProcessingException {
87 return super.writeValueAsString(value);
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
95 @SuppressWarnings("unchecked")
96 public @Nullable <T extends DataObject> Builder<T> getBuilder(Class<T> clazz) {
98 //Class<?> clazzBuilder = getBuilderClass(getBuilderClassName(clazz));
99 return (Builder<T>) builderClazz.newInstance();
100 } catch (InstantiationException | IllegalAccessException e) {
101 LOG.debug("Problem ", e);
107 * Callback for handling mapping failures.
110 public int getMappingFailures() {
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
120 public @Nullable static String toCamelCaseAttributeName(final String name) {
121 if (name == null || name.isEmpty())
124 final StringBuilder ret = new StringBuilder(name.length());
125 if (!name.startsWith("_"))
128 for (final String word : name.split("-")) {
129 if (!word.isEmpty()) {
131 ret.append(Character.toLowerCase(word.charAt(0)));
133 ret.append(Character.toUpperCase(word.charAt(0)));
135 ret.append(word.substring(1));
138 return ret.toString();
141 /** Verify if builder is available
142 * @throws ClassNotFoundException **/
143 public Class<?> assertBuilderClass(Class<?> clazz) throws ClassNotFoundException {
144 return getBuilderClass(getBuilderClassName(clazz));
147 // --- Private functions
150 * Create name of builder class
153 * @return builders class name
154 * @throws ClassNotFoundException
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);
162 // return clazzName + BUILDER;
167 * Search builder in context
170 * @throws ClassNotFoundException
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) {
177 for (Bundle b : context.getBundles()) {
179 return (Class<B>) b.loadClass(name);
180 } catch (ClassNotFoundException e) {
181 // No problem, this bundle doesn't have the class
184 throw new ClassNotFoundException("Can not find Class in OSGi context.");
186 return (Class<B>) Class.forName(name);
188 // not found in any bundle
194 * Adapted Builder callbacks
196 private class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector {
197 private static final long serialVersionUID = 1L;
200 public Class<?> findPOJOBuilder(AnnotatedClass ac) {
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;
205 } else if (ac.getRawType().equals(DateAndTime.class)) {
206 return DateAndTimeBuilder.class;
208 } else if (ac.getRawType().equals(clazz)) {
212 if (ac.getRawType().isInterface()) {
213 String builder = getBuilderClassName(ac.getRawType());
215 Class<?> innerBuilder = getBuilderClass(builder);
217 } catch (ClassNotFoundException e) {
218 // No problem .. try next
221 return super.findPOJOBuilder(ac);
225 public Value findPOJOBuilderConfig(AnnotatedClass ac) {
226 if (ac.hasAnnotation(JsonPOJOBuilder.class)) {
227 return super.findPOJOBuilderConfig(ac);
229 return new JsonPOJOBuilder.Value("build", "set");
233 public static class DateAndTimeBuilder{
235 private final String _value;
237 public DateAndTimeBuilder(String v) {
241 public DateAndTime build() {
242 return new DateAndTime(_value);
246 public static class CustomDateAndTimeSerializer extends StdSerializer<@NonNull DateAndTime>{
248 private static final long serialVersionUID = 1L;
250 public CustomDateAndTimeSerializer() {
253 protected CustomDateAndTimeSerializer(Class<DateAndTime> t) {
258 public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
259 gen.writeString(value.getValue());