1 /***
2 * Copyright 2003-2010 Terracotta, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.ehcache.pool.sizeof.filter;
18
19 import java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.lang.reflect.Field;
24 import java.net.URL;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.Set;
30
31 /***
32 * Filters based on a configuration file
33 *
34 * @author Chris Dennis
35 */
36 public class ResourceSizeOfFilter implements SizeOfFilter {
37
38 private final Set<String> filteredTerms;
39
40 /***
41 * Builds a filter based on the provided configuration URL
42 * @param filterData the URL of the configuration
43 * @throws IOException if it couldn't read the configuration from the URL
44 */
45 public ResourceSizeOfFilter(URL filterData) throws IOException {
46 if (filterData == null) {
47 filteredTerms = Collections.emptySet();
48 } else {
49 InputStream is = filterData.openStream();
50 try {
51 Set<String> filtered = new HashSet<String>();
52 BufferedReader r = new BufferedReader(new InputStreamReader(is));
53 try {
54 while (true) {
55 String field = r.readLine();
56 if (field == null) {
57 break;
58 } else if (!field.startsWith("#")) {
59 filtered.add(field);
60 }
61 }
62 filteredTerms = Collections.unmodifiableSet(filtered);
63 } finally {
64 r.close();
65 }
66 } finally {
67 is.close();
68 }
69 }
70 }
71
72 /***
73 * {@inheritDoc}
74 */
75 public Collection<Field> filterFields(Class<?> klazz, Collection<Field> fields) {
76 for (Iterator<Field> it = fields.iterator(); it.hasNext();) {
77 Field f = it.next();
78 if (filteredTerms.contains(f.getDeclaringClass().getName() + "." + f.getName())) {
79 it.remove();
80 }
81 }
82 return fields;
83 }
84
85 /***
86 * {@inheritDoc}
87 */
88 public boolean filterClass(Class<?> klazz) {
89 return !filteredTerms.contains(klazz.getName());
90 }
91 }