2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.drools.protocol.coders;
23 import com.fasterxml.jackson.annotation.JsonIgnore;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonDeserializationContext;
27 import com.google.gson.JsonDeserializer;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonPrimitive;
30 import com.google.gson.JsonSerializationContext;
31 import com.google.gson.JsonSerializer;
32 import java.lang.reflect.Field;
33 import java.lang.reflect.Method;
34 import java.lang.reflect.Type;
35 import java.time.Instant;
36 import java.time.ZonedDateTime;
37 import java.time.format.DateTimeFormatter;
38 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
39 import org.onap.policy.drools.controller.DroolsController;
40 import org.onap.policy.drools.controller.DroolsControllerConstants;
41 import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * Tools used for encoding/decoding using GSON.
48 class GsonProtocolCoderToolset extends ProtocolCoderToolset {
49 private static final String CANNOT_FETCH_CLASS = "{}: cannot fetch application class {}";
50 private static final String FETCH_CLASS_EX_MSG = "cannot fetch application class ";
55 private static final Logger logger = LoggerFactory.getLogger(GsonProtocolCoderToolset.class);
58 * Formatter for JSON encoding/decoding.
62 public static final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSxxx");
66 public static final DateTimeFormatter zuluFormat = DateTimeFormatter.ISO_INSTANT;
69 * Adapter for ZonedDateTime.
71 public static class GsonUtcAdapter implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> {
73 public ZonedDateTime deserialize(JsonElement element, Type type,
74 JsonDeserializationContext context) {
76 return ZonedDateTime.parse(element.getAsString(), format);
77 } catch (final Exception e) {
78 logger.info("GsonUTCAdapter: cannot parse {} because of {}", element, e.getMessage(), e);
84 public JsonElement serialize(ZonedDateTime datetime, Type type,
85 JsonSerializationContext context) {
86 return new JsonPrimitive(datetime.format(format));
90 public static class GsonInstantAdapter implements JsonSerializer<Instant>, JsonDeserializer<Instant> {
93 public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
94 return Instant.ofEpochMilli(json.getAsLong());
98 public JsonElement serialize(Instant src, Type typeOfSrc, JsonSerializationContext context) {
99 return new JsonPrimitive(src.toEpochMilli());
110 protected final Gson decoder = new GsonBuilder().disableHtmlEscaping()
111 .registerTypeAdapter(ZonedDateTime.class, new GsonUtcAdapter())
112 .registerTypeAdapter(Instant.class, new GsonInstantAdapter()).create();
119 protected final Gson encoder = new GsonBuilder().disableHtmlEscaping()
120 .registerTypeAdapter(ZonedDateTime.class, new GsonUtcAdapter())
121 .registerTypeAdapter(Instant.class, new GsonInstantAdapter()).create();
124 * Toolset to encode/decode tools associated with a topic.
126 * @param eventProtocolParams parameter object for event encoder
127 * @param controllerId controller id
129 public GsonProtocolCoderToolset(EventProtocolParams eventProtocolParams, String controllerId) {
130 super(eventProtocolParams, controllerId);
134 * gets the Gson decoder.
136 * @return the Gson decoder
140 protected Gson getDecoder() {
145 * gets the Gson encoder.
147 * @return the Gson encoder
151 protected Gson getEncoder() {
159 public Object decode(String json) {
161 final DroolsController droolsController =
162 DroolsControllerConstants.getFactory().get(this.groupId, this.artifactId, "");
163 if (droolsController == null) {
164 logger.warn("{}: no drools-controller to process {}", this, json);
165 throw new IllegalStateException("no drools-controller to process event");
168 final CoderFilters decoderFilter = this.filter(json);
169 if (decoderFilter == null) {
170 logger.debug("{}: no decoder to process {}", this, json);
171 throw new UnsupportedOperationException("no decoder to process event");
174 Class<?> decoderClass;
176 decoderClass = droolsController.fetchModelClass(decoderFilter.getCodedClass());
177 if (decoderClass == null) {
178 logger.warn(CANNOT_FETCH_CLASS, this, decoderFilter.getCodedClass());
179 throw new IllegalStateException(
180 FETCH_CLASS_EX_MSG + decoderFilter.getCodedClass());
182 } catch (final Exception e) {
183 logger.warn(CANNOT_FETCH_CLASS, this, decoderFilter.getCodedClass());
184 throw new UnsupportedOperationException(
185 FETCH_CLASS_EX_MSG + decoderFilter.getCodedClass(), e);
188 if (this.customCoder != null) {
190 final Class<?> gsonClassContainer =
191 droolsController.fetchModelClass(this.customCoder.getClassContainer());
192 final Field gsonField = gsonClassContainer.getField(this.customCoder.staticCoderField);
193 final Object gsonObject = gsonField.get(null);
194 final Method fromJsonMethod = gsonObject.getClass().getDeclaredMethod("fromJson",
195 String.class, Class.class);
196 return fromJsonMethod.invoke(gsonObject, json, decoderClass);
197 } catch (final Exception e) {
198 logger.warn(CANNOT_FETCH_CLASS, this, decoderFilter.getCodedClass());
199 throw new UnsupportedOperationException(
200 FETCH_CLASS_EX_MSG + decoderFilter.getCodedClass(), e);
204 return this.decoder.fromJson(json, decoderClass);
205 } catch (final Exception e) {
206 logger.warn("{} cannot decode {} into {}", this, json, decoderClass.getName());
207 throw new UnsupportedOperationException(
208 "cannont decode into " + decoderFilter.getCodedClass(), e);
217 public String encode(Object event) {
219 if (this.customCoder != null) {
221 final DroolsController droolsController =
222 DroolsControllerConstants.getFactory().get(this.groupId, this.artifactId, null);
223 final Class<?> gsonClassContainer =
224 droolsController.fetchModelClass(this.customCoder.getClassContainer());
225 final Field gsonField = gsonClassContainer.getField(this.customCoder.staticCoderField);
226 final Object gsonObject = gsonField.get(null);
227 final Method toJsonMethod =
228 gsonObject.getClass().getDeclaredMethod("toJson", Object.class);
229 return (String) toJsonMethod.invoke(gsonObject, event);
230 } catch (final Exception e) {
231 logger.warn("{} cannot custom-encode {}", this, event);
232 throw new UnsupportedOperationException("event cannot be encoded", e);
236 return this.encoder.toJson(event);
237 } catch (final Exception e) {
238 logger.warn("{} cannot encode {}", this, event);
239 throw new UnsupportedOperationException("event cannot be encoded", e);
245 public String toString() {
246 final StringBuilder builder = new StringBuilder();
247 builder.append("GsonProtocolCoderToolset [toString()=").append(super.toString()).append("]");
248 return builder.toString();