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

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

The newest version!
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 static org.slf4j.LoggerFactory.getLogger;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Map;
import java.util.Set;
import org.bitbucket.gkutiel.in.Filter;
import org.bitbucket.gkutiel.in.Handler;
import org.bitbucket.gkutiel.in.my.mind.feature.Jwt;
import org.bitbucket.gkutiel.in.my.mind.inject.Injector.Selector;
import org.bitbucket.gkutiel.in.my.mind.inject.Injector.Source;
import org.slf4j.Logger;
import io.jsonwebtoken.SignatureException;
import io.netty.handler.codec.http.Cookie;

@SuppressWarnings({ "deprecation", "unchecked" })
public class InjectCookie implements Filter {

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

	static class SourceCookie implements Source, Jwt {
		private final Handler handler;

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

		@Override public  T get(String name, Class type) {
			try {
				final Map> cookies = handler.req().getCookies();
				final Set set = cookies.get(name);
				if (set == null || set.isEmpty()) return null;
				return decode(set.iterator().next().getValue(), type);
			} catch (final SignatureException e) {
				log.warn(e.getMessage(), e);
				return null;
			}
		}
	}

	private static final Logger log = getLogger(InjectCookie.class);
	private static final Selector selectorCookie = target -> getAllFields(target.getClass(), withAnnotation(Co.class));

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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy