001/*
002 * (C) Copyright 2006-2011 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 *     bstefanescu
018 *
019 * $Id$
020 */
021
022package org.nuxeo.common.utils;
023
024/**
025 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
026 */
027public class FilePathPattern {
028
029    private final FileNamePattern[] patterns;
030
031    public FilePathPattern(String path) {
032        this(new Path(path));
033    }
034
035    public FilePathPattern(Path path) {
036        String[] segments = path.segments();
037        patterns = new FileNamePattern[segments.length];
038        for (int i = 0; i < segments.length; i++) {
039            String segment = segments[i];
040            if (segment.equals("**")) {
041                patterns[i] = null; // match any segments
042            } else {
043                patterns[i] = new FileNamePattern(segment);
044            }
045        }
046    }
047
048    public boolean match(String text) {
049        return match(new Path(text));
050    }
051
052    public boolean match(Path path) {
053        int k = 0;
054        String[] segments = path.segments();
055        START: for (int i = 0; i < segments.length; i++) {
056            if (k == patterns.length) {
057                return false;
058            }
059            FileNamePattern pattern = patterns[k];
060            if (pattern == null) { // segment wildcard **
061                k++;
062                if (k == patterns.length) {
063                    return true; // last pattern segment is a wildcard
064                }
065                pattern = patterns[k];
066                while (i < segments.length) {
067                    if (pattern.match(segments[i])) {
068                        k++;
069                        continue START;
070                    }
071                    i++;
072                }
073                return false;
074            } else if (!pattern.match(segments[i])) {
075                return false;
076            } else {
077                k++;
078            }
079        }
080        if (k < patterns.length) {
081            return patterns.length == k + 1 && patterns[k] == null; // match only if last segment is **
082        }
083        return true;
084    }
085
086}