ApiVesrsionCondition.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package com.tzy.common.config.handle;
  2. import com.tzy.common.config.CommonConfig;
  3. import org.slf4j.Logger;
  4. import org.springframework.web.servlet.mvc.condition.RequestCondition;
  5. import org.teasoft.honey.util.StringUtils;
  6. import javax.servlet.http.HttpServletRequest;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9. public class ApiVesrsionCondition implements RequestCondition<ApiVesrsionCondition> {
  10. private static final Logger LOG= org.slf4j.LoggerFactory.getLogger(ApiVesrsionCondition.class);
  11. private final static Pattern VERSION_PREFIX_PATTERN = Pattern.compile("v\\d*\\.\\d*|v\\d+");
  12. private double apiVersion;
  13. public ApiVesrsionCondition(double apiVersion) {
  14. this.apiVersion = apiVersion;
  15. }
  16. @Override
  17. public ApiVesrsionCondition combine(ApiVesrsionCondition other) {
  18. return new ApiVesrsionCondition(other.getApiVersion());
  19. }
  20. @Override
  21. public ApiVesrsionCondition getMatchingCondition(HttpServletRequest request) {
  22. if(CommonConfig.isDevEnv()){
  23. return this;
  24. }
  25. Matcher m = VERSION_PREFIX_PATTERN.matcher(request.getRequestURI());
  26. Boolean flag = m.find();
  27. if (flag) {
  28. String group = m.group();
  29. String v = group.substring(1, group.length());
  30. if(StringUtils.isEmpty(v)){
  31. return null;
  32. }
  33. Double version = Double.parseDouble(v);
  34. if (version == 0) {
  35. if(version <= this.apiVersion){
  36. return this;
  37. }
  38. }
  39. if (version >= this.apiVersion) {
  40. return this;
  41. }
  42. }
  43. return null;
  44. }
  45. @Override
  46. public int compareTo(ApiVesrsionCondition other, HttpServletRequest request) {
  47. LOG.debug("other:{}",other.getApiVersion());
  48. LOG.debug("api version:{}",this.apiVersion);
  49. if(other.getApiVersion() <= this.apiVersion ){
  50. return -1;
  51. }
  52. return 0;
  53. }
  54. public double getApiVersion() {
  55. return apiVersion;
  56. }
  57. }