org.apache.jackrabbit.oak.plugins.observation.filter.GlobbingPathHelper Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.plugins.observation.filter;
import static org.apache.jackrabbit.oak.commons.PathUtils.elements;
import java.util.List;
import com.google.common.collect.Lists;
public class GlobbingPathHelper {
/**
* Converts the provided path containing glob characters *
* and **
into a regular expression. The definition matches
* that of the GlobbingPathFilter with the addition that this conversion
* also supports sub-paths which do not start with a /
.
*
* The rules are:
*
* - leading
**
matches /foo
and bar
* - leading
/**
matches /foo
but not bar
* - intermittent
**
matches zero or any number of path elements
* - trailing
**
matches anything not ending with a /
* - single
*
matches anything except /
* ?
is not a special character
* - anything not a star is wrapped into
\Q...\E
pairs
*
* @param pathWithGlobs path that can contain * and **
* @return a regular expression
* @see GlobbingPathFilter
*/
public static String globPathAsRegex(String pathWithGlobs) {
if (pathWithGlobs == null) {
return null;
} else if (!pathWithGlobs.contains("*")) {
return pathWithGlobs;
}
List elements = Lists.newLinkedList(elements(pathWithGlobs));
StringBuffer sb = new StringBuffer();
sb.append("\\Q");
if (pathWithGlobs.startsWith("/")) {
sb.append("/");
}
if (elements.get(0).equals("**")) {
sb.append("\\E[^/]*(/[^/]*)*\\Q");
elements.remove(0);
}
int size = elements.size();
boolean endsWithStarStar = size == 0 ? false : elements.get(size - 1).equals("**");
if (endsWithStarStar) {
elements.remove(size - 1);
}
boolean addSlash = false;
for(int i=0; i