CodeValueFieldIntrospector.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 java.util.List;
import java.util.Set;

import org.gringlobal.custom.validation.javax.CodeValueField;
import org.springframework.util.ReflectionUtils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.PropertyMetadata;
import com.fasterxml.jackson.databind.PropertyName;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.VirtualAnnotatedMember;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition;

public class CodeValueFieldIntrospector extends AnnotationIntrospector {
	private static final long serialVersionUID = 1L;

	@Override
	public void findAndAddVirtualProperties(MapperConfig<?> config, AnnotatedClass ac, List<BeanPropertyWriter> properties) {

		ReflectionUtils.doWithFields(ac.getType().getRawClass(), field -> {
			CodeValueField annotation = field.getAnnotation(CodeValueField.class);
			if (annotation != null && annotation.indexed()) {
				BeanPropertyWriter bpw = constructVirtualProperty(annotation.value(), field.getName(), config, ac);
				properties.add(bpw);
			}
		});
	}

	private BeanPropertyWriter constructVirtualProperty(String codeValueGroup, String propertyName, MapperConfig<?> config, AnnotatedClass ac) {
		// now, then, we need a placeholder for member (no real Field/Method):
		PropertyName propName = new PropertyName(propertyName + "_cv");
		JavaType type = config.constructType(Set.class);
		AnnotatedMember member = new VirtualAnnotatedMember(ac, ac.getRawType(), propName.getSimpleName(), type);
		// and with that and property definition
		SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(config, member, propName, PropertyMetadata.STD_OPTIONAL, JsonInclude.Include.NON_EMPTY);
		return new CodeValueLangTitlesWriter(codeValueGroup, propertyName, propDef, ac.getAnnotations(), type);
	}

	@Override
	public Version version() {
		return Version.unknownVersion();
	}

}