com.opensymphony.xwork2.util.NamedVariablePatternMatcher 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 com.opensymphony.xwork2.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* An implementation of a pattern matcher that uses simple named wildcards. The named wildcards are defined using the
* {VARIABLE_NAME}
syntax and will match any characters that aren't '/'. Internally, the pattern is
* converted into a regular expression where the named wildcard will be translated into ([^/]+)
so that
* at least one character must match in order for the wildcard to be matched successfully. Matched values will be
* available in the variable map, indexed by the name they were given in the pattern.
*
* For example, the following patterns will be processed as so:
*
*
*
* Pattern
* Example
* Variable Map Contents
*
*
* /animals/{animal}
* /animals/dog
* {animal -> dog}
*
*
* /animals/{animal}/tag/No{id}
* /animals/dog/tag/No23
* {animal -> dog, id -> 23}
*
*
* /{language}
* /en
* {language -> en}
*
*
*
*
* Excaping hasn't been implemented since the intended use of these patterns will be in matching URLs.
*
*
* @since 2.1
*/
public class NamedVariablePatternMatcher implements PatternMatcher {
public boolean isLiteral(String pattern) {
return (pattern == null || pattern.indexOf('{') == -1);
}
/**
* Compiles the pattern.
*
* @param data The pattern, must not be null or empty
* @return The compiled pattern, null if the pattern was null or empty
*/
public CompiledPattern compilePattern(String data) {
StringBuilder regex = new StringBuilder();
if (data != null && data.length() > 0) {
List varNames = new ArrayList<>();
StringBuilder varName = null;
for (int x=0; x map, String data, CompiledPattern expr) {
if (data != null && data.length() > 0) {
Matcher matcher = expr.getPattern().matcher(data);
if (matcher.matches()) {
for (int x=0; x variableNames;
public CompiledPattern(Pattern pattern, List variableNames) {
this.pattern = pattern;
this.variableNames = variableNames;
}
public Pattern getPattern() {
return pattern;
}
public List getVariableNames() {
return variableNames;
}
}
}