001/*
002 * SonarQube
003 * Copyright (C) 2009-2016 SonarSource SA
004 * mailto:contact AT sonarsource DOT com
005 *
006 * This program 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 * This program 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.ExtensionPoint;
025import org.sonar.api.server.ServerSide;
026
027import javax.servlet.Filter;
028
029/**
030 * @since 3.1
031 */
032@ServerSide
033@ExtensionPoint
034public abstract class ServletFilter implements Filter {
035
036  /**
037   * Override to change URL. Default is /*
038   */
039  public UrlPattern doGetPattern() {
040    return UrlPattern.create("/*");
041  }
042
043  public static final class UrlPattern {
044    private int code;
045    private String url;
046    private String urlToMatch;
047
048    private UrlPattern(String url) {
049      Preconditions.checkArgument(!Strings.isNullOrEmpty(url), "Empty url");
050      this.url = url;
051      this.urlToMatch = url.replaceAll("/?\\*", "");
052      if ("/*".equals(url)) {
053        code = 1;
054      } else if (url.startsWith("*")) {
055        code = 2;
056      } else if (url.endsWith("*")) {
057        code = 3;
058      } else {
059        code = 4;
060      }
061    }
062    
063    public static UrlPattern create(String pattern) {
064      return new UrlPattern(pattern);
065    }
066
067    public boolean matches(String path) {
068      switch (code) {
069        case 1:
070          return true;
071        case 2:
072          return path.endsWith(urlToMatch);
073        case 3:
074          return path.startsWith(urlToMatch);
075        default:
076          return path.equals(urlToMatch);
077      }
078    }
079
080    public String getUrl() {
081      return url;
082    }
083
084    @Override
085    public String toString() {
086      return url;
087    }
088  }
089}