CodeValueLangTitlesWriter.java

/*
 * Copyright 2021 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.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.fasterxml.jackson.databind.ser.VirtualBeanPropertyWriter;
import com.fasterxml.jackson.databind.util.Annotations;
import lombok.extern.slf4j.Slf4j;
import org.gringlobal.component.elastic.AppContextHelper;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

@Slf4j
public class CodeValueLangTitlesWriter extends VirtualBeanPropertyWriter {
	private static final long serialVersionUID = 1L;

	private String propName;
	private String codeValueGroup;

	public CodeValueLangTitlesWriter() {
		log.trace("CodeValueLangTitlesWriter");
	}

	public CodeValueLangTitlesWriter(String codeValueGroup, String propName, BeanPropertyDefinition propDef, Annotations annotations, JavaType type) {
		super(propDef, annotations, type);
		this.propName = propName;
		this.codeValueGroup = codeValueGroup;
		log.trace("CodeValueLangTitlesWriter");
	}

	@Override
	protected Object value(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
		Field field = ReflectionUtils.findField(bean.getClass(), propName);
		if (field == null)
			return null;

		ReflectionUtils.makeAccessible(field);
		Object value = field.get(bean);

		if (value != null) {
			return AppContextHelper.findAllTitlesOfCodeValue(codeValueGroup, value.toString());
		}

		return null;
	}

	@Override
	public VirtualBeanPropertyWriter withConfig(MapperConfig<?> config, AnnotatedClass declaringClass, BeanPropertyDefinition propDef, JavaType type) {
		return this;
	}
}