001package org.apache.commons.jcs.engine.match; 002 003/* 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, 015 * software distributed under the License is distributed on an 016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 017 * KIND, either express or implied. See the License for the 018 * specific language governing permissions and limitations 019 * under the License. 020 */ 021 022import org.apache.commons.jcs.engine.match.behavior.IKeyMatcher; 023 024import java.util.HashSet; 025import java.util.Set; 026import java.util.regex.Matcher; 027import java.util.regex.Pattern; 028 029/** This implementation of the KeyMatcher uses standard Java Pattern matching. */ 030public class KeyMatcherPatternImpl<K> 031 implements IKeyMatcher<K> 032{ 033 /** Serial version */ 034 private static final long serialVersionUID = 6667352064144381264L; 035 036 /** 037 * Creates a pattern and find matches on the array. 038 * <p> 039 * @param pattern 040 * @param keyArray 041 * @return Set of the matching keys 042 */ 043 @Override 044 public Set<K> getMatchingKeysFromArray( String pattern, Set<K> keyArray ) 045 { 046 Pattern compiledPattern = Pattern.compile( pattern ); 047 048 Set<K> matchingKeys = new HashSet<K>(); 049 050 // Look for matches 051 for (K key : keyArray) 052 { 053 // TODO we might want to match on the toString. 054 if ( key instanceof String ) 055 { 056 Matcher matcher = compiledPattern.matcher( (String) key ); 057 if ( matcher.matches() ) 058 { 059 matchingKeys.add( key ); 060 } 061 } 062 } 063 064 return matchingKeys; 065 } 066}