All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.conqat.engine.commons.util.NullableAnnotationIntrospectorModule Maven / Gradle / Ivy

There is a newer version: 2025.1.0-rc2
Show newest version
package org.conqat.engine.commons.util;

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Executable;

import org.checkerframework.checker.nullness.qual.Nullable;

import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.AnnotatedParameter;
import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector;
import com.fasterxml.jackson.databind.module.SimpleModule;

/**
 * A per our conventions all fields are required in JSON unless they are
 * annotated with {@link Nullable}. This custom AnnotationIntrospector
 * implements this convention for the schema Jackson infers from the DTOs.
 */
public class NullableAnnotationIntrospectorModule extends SimpleModule {

	private static final long serialVersionUID = 1L;

	@Override
	public void setupModule(SetupContext context) {
		context.insertAnnotationIntrospector(new NullableAnnotationIntrospector());
	}

	/**
	 * Extracts the {@link AnnotatedType} of a field, method or parameter. The
	 * annotated type also knows about
	 * {@link java.lang.annotation.ElementType#TYPE_USE} annotations such as
	 * {@link Nullable}.
	 */
	public static AnnotatedType getAnnotatedTypeForMember(AnnotatedMember member) {
		if (member instanceof AnnotatedField) {
			return ((AnnotatedField) member).getAnnotated().getAnnotatedType();
		} else if (member instanceof AnnotatedMethod) {
			return ((AnnotatedMethod) member).getAnnotated().getAnnotatedReturnType();
		} else if (member instanceof AnnotatedParameter) {
			AnnotatedParameter parameter = (AnnotatedParameter) member;
			int index = parameter.getIndex();
			return ((Executable) parameter.getOwner().getAnnotated()).getAnnotatedParameterTypes()[index];
		}
		throw new IllegalArgumentException(
				"Unexpected member type " + member.getClass() + " for " + member.getName() + "!");
	}

	private static class NullableAnnotationIntrospector extends NopAnnotationIntrospector {

		private static final long serialVersionUID = 1L;

		@Override
		public Boolean hasRequiredMarker(AnnotatedMember member) {
			return !getAnnotatedTypeForMember(member).isAnnotationPresent(Nullable.class);
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy