package com.chenyang.druid.util;

public class ServletPathMatcher implements PatternMatcher {
   private static final ServletPathMatcher INSTANCE = new ServletPathMatcher();

   public static ServletPathMatcher getInstance() {
      return INSTANCE;
   }

   public boolean matches(String pattern, String source) {
      if (pattern != null && source != null) {
         pattern = pattern.trim();
         source = source.trim();
         if (pattern.endsWith("*")) {
            int length = pattern.length() - 1;
            if (source.length() >= length && pattern.substring(0, length).equals(source.substring(0, length))) {
               return true;
            }
         } else if (pattern.startsWith("*")) {
            int length = pattern.length() - 1;
            if (source.length() >= length && source.endsWith(pattern.substring(1))) {
               return true;
            }
         } else if (pattern.contains("*")) {
            int start = pattern.indexOf("*");
            int end = pattern.lastIndexOf("*");
            if (source.startsWith(pattern.substring(0, start)) && source.endsWith(pattern.substring(end + 1))) {
               return true;
            }
         } else if (pattern.equals(source)) {
            return true;
         }

         return false;
      } else {
         return false;
      }
   }
}
