EntityRefDeserializerModifier.java

/*
 * Copyright 2023 Global Crop Diversity Trust
 *
 * 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.
 */
package org.gringlobal.custom.json;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.BeanDeserializer;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import lombok.extern.slf4j.Slf4j;

import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import java.util.Objects;

@Slf4j
public class EntityRefDeserializerModifier extends BeanDeserializerModifier {

	@Override
	public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> jsonDeserializer) {
		if (jsonDeserializer instanceof BeanDeserializer) {
			BeanDeserializer beanDeserializer = (BeanDeserializer) jsonDeserializer;
			beanDeserializer.properties().forEachRemaining(settableBeanProperty -> {
				if (isEntityRef(settableBeanProperty)) {
					EntityRefDeserializer<?> deserializer = new EntityRefDeserializer<>();
					deserializer.setWrapperType(settableBeanProperty.getType());
					deserializer.setRefType(config.getTypeFactory().constructParametricType(EntityRefDeserializer.EntityRef.class, settableBeanProperty.getType()));
					try {
						deserializer.setConstructor(settableBeanProperty.getType().getRawClass().getConstructor(Long.class));
						beanDeserializer.replaceProperty(settableBeanProperty, settableBeanProperty.withValueDeserializer(deserializer));
					} catch (NoSuchMethodException | SecurityException e) {
						log.warn("Exception in modifying deserializer to EntityRefDeserializer", e);
					}
				}
			});
		}
		return jsonDeserializer;
	}

	private boolean isEntityRef(SettableBeanProperty settableBeanProperty) {
		return Objects.isNull(settableBeanProperty.getAnnotation(IgnoreEntityRefDeserializer.class)) && 
			(Objects.nonNull(settableBeanProperty.getAnnotation(ManyToOne.class)) || Objects.nonNull(settableBeanProperty.getAnnotation(OneToOne.class)));
	}
}