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.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 public static UrlPattern create(String pattern) { 049 return new UrlPattern(pattern); 050 } 051 052 private UrlPattern(String url) { 053 Preconditions.checkArgument(!Strings.isNullOrEmpty(url), "Empty url"); 054 this.url = url; 055 this.urlToMatch = url.replaceAll("/?\\*", ""); 056 if ("/*".equals(url)) { 057 code = 1; 058 } else if (url.startsWith("*")) { 059 code = 2; 060 } else if (url.endsWith("*")) { 061 code = 3; 062 } else { 063 code = 4; 064 } 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}