Skip to content

Instantly share code, notes, and snippets.

@nyilmaz
Last active August 29, 2015 13:56
Show Gist options
  • Save nyilmaz/8853111 to your computer and use it in GitHub Desktop.
Save nyilmaz/8853111 to your computer and use it in GitHub Desktop.
package magnet.support.spring.captchaextension.annotation;
import com.google.common.base.CaseFormat;
import magnet.support.spring.captchaextension.RequestMappingInfoAppendableHandlerMapping;
import magnet.support.spring.captchaextension.service.CaptchaService;
import magnet.support.spring.captchaextension.service.impl.CaptchaServiceImpl;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethodSelector;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.Set;
/**
* @author nyilmaz
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(EnableCaptcha.CaptchaConfiguration.class)
public @interface EnableCaptcha {
public String[] value() default "/captcha.jpg";
@Configuration
class CaptchaConfiguration {
private static final Logger logger = LoggerFactory.getLogger(CaptchaConfiguration.class);
@Autowired
RequestMappingInfoAppendableHandlerMapping mapping;
// @Bean
// public SimpleControllerHandlerAdapter simpleControllerHandlerAdapter() {
// return new SimpleControllerHandlerAdapter();
// }
//
// @Bean
// public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
//
// SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
// CaptchaController controllerBean = context.getBean(CaptchaController.class);
// Map<String, Object> urlMapping = Maps.newHashMap();
//
// Map<String, Object> captchaEnabledBeans = context.getBeansWithAnnotation(EnableCaptcha.class);
//
// for(String s : captchaEnabledBeans.keySet()) {
// String[] urls = context.findAnnotationOnBean(s, EnableCaptcha.class).value();
// for(String url : urls) {
// urlMapping.put(url, controllerBean);
// logger.info("Captcha urls added: url:{}, handler:{}", url, s);
// }
// }
//
// simpleUrlHandlerMapping.setUrlMap(urlMapping);
// return simpleUrlHandlerMapping;
// }
@Bean
public CaptchaService captchaService() {
return new CaptchaServiceImpl();
}
// @Override
// public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
// BeanDefinition beanDefinition = new RootBeanDefinition(CaptchaController.class, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true);
// registry.registerBeanDefinition(
// CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, CaptchaController.class.getName()),
// beanDefinition
// );
// }
@PostConstruct
public void deneme() {
final CaptchaController captchaController = new CaptchaController();
Set<Method> methods = HandlerMethodSelector.selectMethods(captchaController.getClass(), new ReflectionUtils.MethodFilter() {
@Override
public boolean matches(Method method) {
return mapping.getMappingForMethod(method, captchaController.getClass()) != null;
}
});
for(Method method : methods) {
RequestMappingInfo info = new RequestMappingInfo(new PatternsRequestCondition("/asd"),
new RequestMethodsRequestCondition(RequestMethod.GET),
null,
null,
null,
null,
null);
mapping.registerHandlerMethod(info, method, info);
}
}
// @Override
// public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
//
//
// }
}
// @Controller
class CaptchaController {
private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);
private static final Integer TEXT_LENGTH = 5;
@Autowired
CaptchaService captchaService;
//@RequestMapping(value = {"/capthca.jpg", "/captcha.png"})
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String code = RandomStringUtils.randomAlphanumeric(TEXT_LENGTH);
byte[] captchaAsBytes;
try {
captchaAsBytes = captchaService.generate(code);
captchaService.saveCaptchaCode(code, session);
response.setContentType(MediaType.IMAGE_PNG_VALUE);
response.setStatus(HttpServletResponse.SC_CREATED);
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(captchaAsBytes);
outputStream.flush();
} catch(IOException e) {
logger.error("Cannot generate captcha.");
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment