KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cayenne > tools > NamePatternMatcher


1 /*****************************************************************
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  ****************************************************************/

19
20 package org.apache.cayenne.tools;
21
22 import java.util.ArrayList JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.StringTokenizer JavaDoc;
26 import java.util.regex.Pattern JavaDoc;
27 import java.util.regex.PatternSyntaxException JavaDoc;
28
29 import org.apache.cayenne.util.CayenneMapEntry;
30
31 /**
32  * Provides name pattern matching functionality.
33  *
34  * @author Andrus Adamchik, Mike Kienenberger
35  * @since 1.2
36  */

37 public class NamePatternMatcher {
38
39     protected ILog logger;
40
41     protected Pattern JavaDoc[] itemIncludeFilters;
42     protected Pattern JavaDoc[] itemExcludeFilters;
43
44     public NamePatternMatcher(ILog parentTask, String JavaDoc includePattern,
45             String JavaDoc excludePattern) {
46         this.logger = parentTask;
47         this.itemIncludeFilters = createPatterns(includePattern);
48         this.itemExcludeFilters = createPatterns(excludePattern);
49     }
50
51     /**
52      * Returns an array of Patterns. Takes a comma-separated list of patterns, attempting
53      * to convert them to the java.util.regex.Pattern syntax. E.g.
54      * <p>
55      * <code>"billing_*,user?"</code> will become an array of two expressions:
56      * <p>
57      * <code>^billing_.*$</code><br>
58      * <code>^user.?$</code><br>
59      */

60     public Pattern JavaDoc[] createPatterns(String JavaDoc patternString) {
61         String JavaDoc[] patternStrings = tokenizePattern(patternString);
62         List JavaDoc patterns = new ArrayList JavaDoc(patternStrings.length);
63
64         for (int i = 0; i < patternStrings.length; i++) {
65
66             // test the pattern
67
try {
68                 patterns.add(Pattern.compile(patternStrings[i]));
69             }
70             catch (PatternSyntaxException JavaDoc e) {
71
72                 if (logger != null) {
73                     logger.log("Ignoring invalid pattern ["
74                             + patternStrings[i]
75                             + "], reason: "
76                             + e.getMessage(), ILog.MSG_WARN);
77                 }
78                 continue;
79             }
80         }
81
82         return (Pattern JavaDoc[]) patterns.toArray(new Pattern JavaDoc[patterns.size()]);
83     }
84
85     /**
86      * Returns an array of valid regular expressions. Takes a comma-separated list of
87      * patterns, attempting to convert them to the java.util.regex.Pattern syntax. E.g.
88      * <p>
89      * <code>"billing_*,user?"</code> will become an array of two expressions:
90      * <p>
91      * <code>^billing_.*$</code><br>
92      * <code>^user.?$</code><br>
93      */

94     public String JavaDoc[] tokenizePattern(String JavaDoc pattern) {
95         if (pattern != null && pattern.length() > 0) {
96             StringTokenizer JavaDoc toks = new StringTokenizer JavaDoc(pattern, ",");
97
98             int len = toks.countTokens();
99             if (len == 0) {
100                 return new String JavaDoc[0];
101             }
102
103             List JavaDoc patterns = new ArrayList JavaDoc(len);
104             for (int i = 0; i < len; i++) {
105                 String JavaDoc nextPattern = toks.nextToken();
106                 StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
107
108                 // convert * into regex syntax
109
// e.g. abc*x becomes ^abc.*x$
110
// or abc?x becomes ^abc.?x$
111
buffer.append("^");
112                 for (int j = 0; j < nextPattern.length(); j++) {
113                     char nextChar = nextPattern.charAt(j);
114                     if (nextChar == '*' || nextChar == '?') {
115                         buffer.append('.');
116                     }
117                     buffer.append(nextChar);
118                 }
119                 buffer.append("$");
120                 patterns.add(buffer.toString());
121             }
122
123             return (String JavaDoc[]) patterns.toArray(new String JavaDoc[patterns.size()]);
124         }
125         else {
126             return new String JavaDoc[0];
127         }
128     }
129
130     /**
131      * Applies preconfigured list of filters to the list, removing entities that do not
132      * pass the filter.
133      */

134     protected List JavaDoc filter(List JavaDoc items) {
135         if (items == null || items.isEmpty()) {
136             return items;
137         }
138
139         if ((itemIncludeFilters.length == 0) && (itemExcludeFilters.length == 0)) {
140             return items;
141         }
142
143         Iterator JavaDoc it = items.iterator();
144         while (it.hasNext()) {
145             CayenneMapEntry entity = (CayenneMapEntry) it.next();
146
147             if (!passedIncludeFilter(entity)) {
148                 it.remove();
149                 continue;
150             }
151
152             if (!passedExcludeFilter(entity)) {
153                 it.remove();
154                 continue;
155             }
156         }
157
158         return items;
159     }
160
161     /**
162      * Returns true if the entity matches any one of the "include" patterns, or if there
163      * is no "include" patterns defined.
164      */

165     protected boolean passedIncludeFilter(CayenneMapEntry item) {
166         if (itemIncludeFilters.length == 0) {
167             return true;
168         }
169
170         String JavaDoc itemName = item.getName();
171         for (int i = 0; i < itemIncludeFilters.length; i++) {
172             if (itemIncludeFilters[i].matcher(itemName).find()) {
173                 return true;
174             }
175         }
176
177         return false;
178     }
179
180     /**
181      * Returns true if the entity does not match any one of the "exclude" patterns, or if
182      * there is no "exclude" patterns defined.
183      */

184     protected boolean passedExcludeFilter(CayenneMapEntry item) {
185         if (itemExcludeFilters.length == 0) {
186             return true;
187         }
188
189         String JavaDoc itemName = item.getName();
190         for (int i = 0; i < itemExcludeFilters.length; i++) {
191             if (itemExcludeFilters[i].matcher(itemName).find()) {
192                 return false;
193             }
194         }
195
196         return true;
197     }
198
199     public static String JavaDoc replaceWildcardInStringWithString(
200             String JavaDoc wildcard,
201             String JavaDoc pattern,
202             String JavaDoc replacement) {
203         if (null == pattern || null == wildcard)
204             return pattern;
205
206         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
207         int lastPos = 0;
208         int wildCardPos = pattern.indexOf(wildcard);
209         while (-1 != wildCardPos) {
210             if (lastPos != wildCardPos) {
211                 buffer.append(pattern.substring(lastPos, wildCardPos));
212             }
213             buffer.append(replacement);
214             lastPos += wildCardPos + wildcard.length();
215             wildCardPos = pattern.indexOf(wildcard, lastPos);
216         }
217
218         if (lastPos < pattern.length()) {
219             buffer.append(pattern.substring(lastPos));
220         }
221
222         return buffer.toString();
223     }
224 }
225
Popular Tags