001/*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar 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 * Sonar 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
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019 */
020package org.sonar.api.web;
021
022import com.google.common.annotations.Beta;
023import com.google.common.base.Preconditions;
024import com.google.common.base.Strings;
025import org.sonar.api.ServerExtension;
026
027import javax.servlet.Filter;
028
029/**
030 * @since 3.1
031 */
032@Beta
033public abstract class ServletFilter implements ServerExtension, Filter {
034
035  /**
036   * Override to change URL. Default is /*
037   */
038  public UrlPattern doGetPattern() {
039    return UrlPattern.create("/*");
040  }
041
042  public static final class UrlPattern {
043    private int code;
044    private String url;
045    private String urlToMatch;
046
047    public static UrlPattern create(String pattern) {
048      return new UrlPattern(pattern);
049    }
050
051    private UrlPattern(String url) {
052      Preconditions.checkArgument(!Strings.isNullOrEmpty(url), "Empty url");
053      this.url = url;
054      this.urlToMatch = url.replaceAll("/?\\*", "");
055      if ("/*".equals(url)) {
056        code = 1;
057      } else if (url.startsWith("*")) {
058        code = 2;
059      } else if (url.endsWith("*")) {
060        code = 3;
061      } else {
062        code = 4;
063      }
064    }
065
066    public boolean matches(String path) {
067      switch (code) {
068        case 1:
069          return true;
070        case 2:
071          return path.endsWith(urlToMatch);
072        case 3:
073          return path.startsWith(urlToMatch);
074        default:
075          return path.equals(urlToMatch);
076      }
077    }
078
079    public String getUrl() {
080      return url;
081    }
082
083    @Override
084    public String toString() {
085      return url;
086    }
087  }
088}