All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dk.eobjects.metamodel.query.WildcardPattern Maven / Gradle / Ivy

/**
 *  This file is part of MetaModel.
 *
 *  MetaModel is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MetaModel is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MetaModel.  If not, see .
 */
package dk.eobjects.metamodel.query;

import java.io.Serializable;
import java.util.StringTokenizer;

/**
 * Represents a pattern with a wildcard character. These are typically used in
 * FilterItems with the LIKE operator.
 * 
 * @see FilterItem
 */
public class WildcardPattern implements Serializable {

	private static final long serialVersionUID = 857462137797209624L;
	private String _pattern;
	private char _wildcard;
	private boolean _endsWithDelim;

	public WildcardPattern(String pattern, char wildcard) {
		_pattern = pattern;
		_wildcard = wildcard;
		_endsWithDelim = (_pattern.charAt(pattern.length() - 1) == _wildcard);
	}

	public boolean matches(String value) {
		if (value == null) {
			return false;
		}
		StringTokenizer st = new StringTokenizer(_pattern, Character
				.toString(_wildcard));
		int charIndex = 0;
		while (st.hasMoreTokens()) {
			String token = st.nextToken();
			charIndex = value.indexOf(token, charIndex);
			if (charIndex == -1) {
				return false;
			}
			charIndex = charIndex + token.length();
		}
		if (!_endsWithDelim) {
			// Unless the last char of the pattern is a wildcard, we need to
			// have reached the end of the string
			if (charIndex != value.length()) {
				return false;
			}
		}
		return true;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy