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

org.bitbucket.gkutiel.in.my.mind.inject.InjectParam Maven / Gradle / Ivy

package org.bitbucket.gkutiel.in.my.mind.inject;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.reflections.ReflectionUtils.getAllFields;
import static org.reflections.ReflectionUtils.withAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.List;
import org.bitbucket.gkutiel.in.Filter;
import org.bitbucket.gkutiel.in.Handler;
import org.bitbucket.gkutiel.in.my.mind.inject.Injector.Selector;
import org.bitbucket.gkutiel.in.my.mind.inject.Injector.Source;
import com.google.gson.Gson;

@SuppressWarnings("unchecked")
public class InjectParam implements Filter {

	@Retention(RUNTIME)
	@Target(FIELD)
	public @interface In {}

	static class SourceParam implements Source {

		private final Handler handler;

		public SourceParam(Handler handler) {
			this.handler = handler;
		}

		@Override public  T get(String name, Class type) {
			final List vals = handler.req().getQueryParameters().get(name);
			if (vals == null || vals.isEmpty()) return null;

			final String val = vals.get(0);
			return type.equals(String.class) ? (T) val : gson.fromJson(val, type);
		}
	}

	private static final Gson gson = new Gson();
	private static final Selector selectorIn = target -> getAllFields(target.getClass(), withAnnotation(In.class));

	@Override public void filter(final Handler handler) {
		new Injector(selectorIn, new SourceParam(handler)).inject(handler);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy