001/*
002 * SonarQube, open source software quality management tool.
003 * Copyright (C) 2008-2014 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * SonarQube is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * SonarQube is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019 */
020package org.sonar.api.web;
021
022import com.google.common.base.Preconditions;
023import com.google.common.base.Strings;
024import org.sonar.api.ServerExtension;
025
026import javax.servlet.Filter;
027
028/**
029 * @since 3.1
030 */
031public abstract class ServletFilter implements ServerExtension, Filter {
032
033  /**
034   * Override to change URL. Default is /*
035   */
036  public UrlPattern doGetPattern() {
037    return UrlPattern.create("/*");
038  }
039
040  public static final class UrlPattern {
041    private int code;
042    private String url;
043    private String urlToMatch;
044
045    public static UrlPattern create(String pattern) {
046      return new UrlPattern(pattern);
047    }
048
049    private UrlPattern(String url) {
050      Preconditions.checkArgument(!Strings.isNullOrEmpty(url), "Empty url");
051      this.url = url;
052      this.urlToMatch = url.replaceAll("/?\\*", "");
053      if ("/*".equals(url)) {
054        code = 1;
055      } else if (url.startsWith("*")) {
056        code = 2;
057      } else if (url.endsWith("*")) {
058        code = 3;
059      } else {
060        code = 4;
061      }
062    }
063
064    public boolean matches(String path) {
065      switch (code) {
066        case 1:
067          return true;
068        case 2:
069          return path.endsWith(urlToMatch);
070        case 3:
071          return path.startsWith(urlToMatch);
072        default:
073          return path.equals(urlToMatch);
074      }
075    }
076
077    public String getUrl() {
078      return url;
079    }
080
081    @Override
082    public String toString() {
083      return url;
084    }
085  }
086}