001/* 002 * (C) Copyright 2006-2007 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nuxeo - initial API and implementation 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.runtime.deployment.preprocessor.install.filters; 023 024import org.nuxeo.common.utils.Path; 025import org.nuxeo.common.utils.PathFilter; 026 027/** 028 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 029 */ 030public abstract class AbstractFilter implements PathFilter { 031 032 protected final Path pattern; 033 034 protected AbstractFilter(Path pattern) { 035 this.pattern = pattern; 036 } 037 038 public boolean accept(Path path, boolean defaultPolicy) { 039 // path should be in canonical form 040 boolean match = segmentsMatch(pattern, path); 041 return match ? !defaultPolicy : defaultPolicy; 042 } 043 044 protected static boolean segmentsMatch(Path pattern, Path path) { 045 int patternLen = pattern.segmentCount(); 046 int k = 0; 047 for (int i = 0, len = path.segmentCount(); i < len; i++) { 048 if (k >= patternLen) { 049 return false; 050 } 051 String segPattern = pattern.segment(k); 052 String segment = path.segment(i); 053 if (segPattern.equals("**")) { 054 k++; 055 if (k == patternLen) { 056 return true; 057 } 058 // skip non matching segments 059 String match = pattern.segment(k); 060 for (; i < len; i++) { 061 if (segmentMatch(match, path.segment(i))) { 062 k++; 063 break; 064 } 065 } 066 } else if (segmentMatch(segPattern, segment)) { 067 k++; 068 } else { 069 return false; 070 } 071 } 072 return k >= patternLen; 073 } 074 075 public static boolean segmentMatch(String pattern, String segment) { 076 if (pattern.equals("*")) { 077 return true; 078 } 079 int p = pattern.indexOf('*'); 080 if (p == -1) { 081 return pattern.equals(segment); 082 } 083 if (p == 0) { 084 if (!segment.endsWith(pattern.substring(1))) { 085 return false; 086 } 087 } else if (p == pattern.length() - 1) { 088 if (!segment.startsWith(pattern.substring(0, p))) { 089 return false; 090 } 091 } else { 092 String prefix = pattern.substring(0, p); 093 String suffix = pattern.substring(p + 1); 094 if (!segment.startsWith(prefix) || !segment.endsWith(suffix)) { 095 return false; 096 } 097 } 098 return true; 099 } 100 101}