2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 Nordix Foundation.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
20 package org.onap.dcaegen2.services.pmmapper.utils;
22 import com.google.gson.Gson;
23 import com.google.gson.JsonDeserializationContext;
24 import com.google.gson.JsonDeserializer;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonParseException;
28 import lombok.NonNull;
30 import java.lang.reflect.Field;
31 import java.lang.reflect.Type;
32 import java.util.List;
33 import java.util.Optional;
34 import java.util.stream.Stream;
38 * Extension of the default deserializer with support for GSONRequired annotation.
39 * @param <T> Type of object for deserialization process.
41 public class RequiredFieldDeserializer<T> implements JsonDeserializer<T> {
44 public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) {
45 T obj = new Gson().fromJson(jsonElement, type);
46 validateRequiredFields(obj.getClass().getDeclaredFields(), obj);
50 private void validateRequiredFields(@NonNull Field[] fields, @NonNull Object pojo) {
51 if (pojo instanceof List) {
52 final List<?> pojoList = (List<?>) pojo;
53 for (final Object pojoListPojo : pojoList) {
54 validateRequiredFields(pojoListPojo.getClass().getDeclaredFields(), pojoListPojo);
59 .filter(field -> field.getAnnotation(GSONRequired.class) != null)
62 field.setAccessible(true);
63 Object fieldObj = Optional.ofNullable(field.get(pojo))
64 .orElseThrow(()-> new JsonParseException(
65 String.format("Field '%s' in class '%s' is required but not found.",
66 field.getName(), pojo.getClass().getSimpleName())));
68 Field[] declaredFields = fieldObj.getClass().getDeclaredFields();
69 validateRequiredFields(declaredFields, fieldObj);
71 catch (Exception exception) {
72 throw new JsonParseException("Failed to check fields.", exception);