01: package org.apache.lucene.search;
02:
03: /**
04: * Copyright 2005 The Apache Software Foundation
05: *
06: * Licensed under the Apache License, Version 2.0 (the "License");
07: * you may not use this file except in compliance with the License.
08: * You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS,
14: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15: * See the License for the specific language governing permissions and
16: * limitations under the License.
17: */
18:
19: import org.apache.lucene.index.IndexReader;
20:
21: import java.io.IOException;
22: import java.util.BitSet;
23: import java.util.Map;
24: import java.util.WeakHashMap;
25:
26: /**
27: * Wraps another SpanFilter's result and caches it. The purpose is to allow
28: * filters to simply filter, and then wrap with this class to add caching.
29: */
30: public class CachingSpanFilter extends SpanFilter {
31: protected SpanFilter filter;
32:
33: /**
34: * A transient Filter cache. To cache Filters even when using {@link org.apache.lucene.search.RemoteSearchable} use
35: * {@link org.apache.lucene.search.RemoteCachingWrapperFilter} instead.
36: */
37: protected transient Map cache;
38:
39: /**
40: * @param filter Filter to cache results of
41: */
42: public CachingSpanFilter(SpanFilter filter) {
43: this .filter = filter;
44: }
45:
46: public BitSet bits(IndexReader reader) throws IOException {
47: SpanFilterResult result = getCachedResult(reader);
48: return result != null ? result.getBits() : null;
49: }
50:
51: private SpanFilterResult getCachedResult(IndexReader reader)
52: throws IOException {
53: SpanFilterResult result = null;
54: if (cache == null) {
55: cache = new WeakHashMap();
56: }
57:
58: synchronized (cache) { // check cache
59: result = (SpanFilterResult) cache.get(reader);
60: if (result == null) {
61: result = filter.bitSpans(reader);
62: cache.put(reader, result);
63: }
64: }
65: return result;
66: }
67:
68: public SpanFilterResult bitSpans(IndexReader reader)
69: throws IOException {
70: return getCachedResult(reader);
71: }
72:
73: public String toString() {
74: return "CachingSpanFilter(" + filter + ")";
75: }
76:
77: public boolean equals(Object o) {
78: if (!(o instanceof CachingSpanFilter))
79: return false;
80: return this .filter.equals(((CachingSpanFilter) o).filter);
81: }
82:
83: public int hashCode() {
84: return filter.hashCode() ^ 0x1117BF25;
85: }
86: }
|