aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/wt/data-provider/provider/src/main/java/org/onap/ccsdk/features/sdnr/wt/dataprovider/yangtools/YangToolsMapper2.java
blob: 814bfd7450da404d746ebb2454bd0ab9a6cc3570 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*
 * ============LICENSE_START=======================================================
 * ONAP : ccsdk features
 * ================================================================================
 * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
 * All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 *
 */
package org.onap.ccsdk.features.sdnr.wt.dataprovider.yangtools;

import java.io.IOException;
import javax.annotation.Nullable;

import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
import org.opendaylight.yangtools.concepts.Builder;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder.Value;
import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;

/**
 * YangToolsMapper is a specific Jackson mapper configuration for opendaylight yangtools serialization or
 * deserialization of DataObject to/from JSON TODO ChoiceIn and Credentials deserialization only for
 * LoginPasswordBuilder
 */
public class YangToolsMapper2<T extends DataObject> extends ObjectMapper {

    private final Logger LOG = LoggerFactory.getLogger(YangToolsMapper2.class);
    private static final long serialVersionUID = 1L;
    private static String BUILDER = "Builder";

    private @Nullable final Class<T> clazz;
    private @Nullable final Class<? extends Builder<? extends T>> builderClazz;

    private BundleContext context;

    /**
     * Generic Object creation of yangtools java class builder pattern.
     * 
     * @param <X> Class of DataObject
     * @param <B> Builder for the class.
     * @param clazz specifies class to be mapped
     * @param builderClazz is the builder for class with name pattern "clazzBuilder".<br>
     *        If null the clazz is expected to support normal jackson build pattern.
     * @throws ClassNotFoundException if builderClazz not available in bundle
     */
    public <X extends T, B extends Builder<X>> YangToolsMapper2(@NonNull Class<T> clazz,
            @Nullable Class<B> builderClazz) throws ClassNotFoundException {
        super();
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
        setSerializationInclusion(Include.NON_NULL);
        setAnnotationIntrospector(new YangToolsBuilderAnnotationIntrospector());
        SimpleModule dateAndTimeSerializerModule = new SimpleModule();
        dateAndTimeSerializerModule.addSerializer(DateAndTime.class, new CustomDateAndTimeSerializer());
        registerModule(dateAndTimeSerializerModule);
        Bundle bundle = FrameworkUtil.getBundle(YangToolsMapper2.class);

        this.clazz = clazz;
        this.builderClazz = builderClazz != null ? builderClazz : getBuilderClass(getBuilderClassName(clazz));
        context = bundle != null ? bundle.getBundleContext() : null;
    }

    @Override
    public String writeValueAsString(Object value) throws JsonProcessingException {
        return super.writeValueAsString(value);
    }

    /**
     * Get Builder object for yang tools interface.
     * 
     * @param <T> yang-tools base datatype
     * @param clazz class with interface.
     * @return builder for interface or null if not existing
     */
    public @Nullable Builder<? extends T> getBuilder(Class<T> clazz) {
        try {
            if (builderClazz != null)
                return (Builder<? extends T>) builderClazz.newInstance();
            else
                return null;
        } catch (InstantiationException | IllegalAccessException e) {
            LOG.debug("Problem ", e);
            return null;
        }
    }

    /**
     * Callback for handling mapping failures.
     * 
     * @return
     */
    public int getMappingFailures() {
        return 0;
    }

    /**
     * Provide mapping of string to attribute names, generated by yang-tools. "netconf-id" converted to "_netconfId"
     * 
     * @param name with attribute name, not null or empty
     * @return converted string or null if name was empty or null
     */
    public @Nullable static String toCamelCaseAttributeName(final String name) {
        if (name == null || name.isEmpty())
            return null;

        final StringBuilder ret = new StringBuilder(name.length());
        if (!name.startsWith("_"))
            ret.append('_');
        int start = 0;
        for (final String word : name.split("-")) {
            if (!word.isEmpty()) {
                if (start++ == 0) {
                    ret.append(Character.toLowerCase(word.charAt(0)));
                } else {
                    ret.append(Character.toUpperCase(word.charAt(0)));
                }
                ret.append(word.substring(1));
            }
        }
        return ret.toString();
    }

    /**
     * Verify if builder is available
     * 
     * @throws ClassNotFoundException
     **/
    public Class<?> assertBuilderClass(Class<?> clazz) throws ClassNotFoundException {
        return getBuilderClass(getBuilderClassName(clazz));
    }

    // --- Private functions

    /**
     * Create name of builder class
     * 
     * @param <T>
     * @param clazz
     * @return builders class name
     * @throws ClassNotFoundException
     */
    private static String getBuilderClassName(Class<?> clazz) {
        return clazz.getName() + BUILDER;
    }

    /**
     * Search builder in context
     * 
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @SuppressWarnings("unchecked")
    private <X extends T, B extends Builder<X>> Class<B> getBuilderClass(String name) throws ClassNotFoundException {
        // Try to find in other bundles
        if (context != null) {
            //OSGi environment
            for (Bundle b : context.getBundles()) {
                try {
                    return (Class<B>) b.loadClass(name);
                } catch (ClassNotFoundException e) {
                    // No problem, this bundle doesn't have the class
                }
            }
            throw new ClassNotFoundException("Can not find Class in OSGi context.");
        } else {
            return (Class<B>) Class.forName(name);
        }
        // not found in any bundle
    }

    // --- Classes

    /**
     * Adapted Builder callbacks
     */
    private class YangToolsBuilderAnnotationIntrospector extends JacksonAnnotationIntrospector {
        private static final long serialVersionUID = 1L;

        @Override
        public Class<?> findPOJOBuilder(AnnotatedClass ac) {

            if (ac.getRawType().equals(Credentials.class)) {
                return org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPasswordBuilder.class;

            } else if (ac.getRawType().equals(DateAndTime.class)) {
                return DateAndTimeBuilder.class;

            } else if (ac.getRawType().equals(clazz)) {
                return builderClazz;
            }

            if (ac.getRawType().isInterface()) {
                String builder = getBuilderClassName(ac.getRawType());
                try {
                    Class<?> innerBuilder = getBuilderClass(builder);
                    return innerBuilder;
                } catch (ClassNotFoundException e) {
                    // No problem .. try next
                }
            }
            return super.findPOJOBuilder(ac);
        }

        @Override
        public Value findPOJOBuilderConfig(AnnotatedClass ac) {
            if (ac.hasAnnotation(JsonPOJOBuilder.class)) {
                return super.findPOJOBuilderConfig(ac);
            }
            return new JsonPOJOBuilder.Value("build", "set");
        }
    }

    public static class DateAndTimeBuilder {

        private final String _value;

        public DateAndTimeBuilder(String v) {
            this._value = v;
        }

        public DateAndTime build() {
            return new DateAndTime(_value);
        }

    }
    public static class CustomDateAndTimeSerializer extends StdSerializer<@NonNull DateAndTime> {

        private static final long serialVersionUID = 1L;

        public CustomDateAndTimeSerializer() {
            this(null);
        }

        protected CustomDateAndTimeSerializer(Class<DateAndTime> t) {
            super(t);
        }

        @Override
        public void serialize(DateAndTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.getValue());
        }

    }
}