1
package org.apache.lucene.analysis;
4
* Licensed to the Apache Software Foundation (ASF) under one or more
5
* contributor license agreements. See the NOTICE file distributed with
6
* this work for additional information regarding copyright ownership.
7
* The ASF licenses this file to You under the Apache License, Version 2.0
8
* (the "License"); you may not use this file except in compliance with
9
* the License. You may obtain a copy of the License at
11
* http://www.apache.org/licenses/LICENSE-2.0
13
* Unless required by applicable law or agreed to in writing, software
14
* distributed under the License is distributed on an "AS IS" BASIS,
15
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
* See the License for the specific language governing permissions and
17
* limitations under the License.
20
import java.io.IOException;
21
import java.util.Iterator;
22
import java.util.LinkedList;
23
import java.util.List;
25
import org.apache.lucene.util.AttributeSource;
28
* This class can be used if the token attributes of a TokenStream
29
* are intended to be consumed more than once. It caches
30
* all token attribute states locally in a List.
32
* <P>CachingTokenFilter implements the optional method
33
* {@link TokenStream#reset()}, which repositions the
34
* stream to the first Token.
36
public final class CachingTokenFilter extends TokenFilter {
37
private List<AttributeSource.State> cache = null;
38
private Iterator<AttributeSource.State> iterator = null;
39
private AttributeSource.State finalState;
41
public CachingTokenFilter(TokenStream input) {
46
public final boolean incrementToken() throws IOException {
49
cache = new LinkedList<AttributeSource.State>();
51
iterator = cache.iterator();
54
if (!iterator.hasNext()) {
55
// the cache is exhausted, return false
58
// Since the TokenFilter can be reset, the tokens need to be preserved as immutable.
59
restoreState(iterator.next());
64
public final void end() throws IOException {
65
if (finalState != null) {
66
restoreState(finalState);
71
public void reset() throws IOException {
73
iterator = cache.iterator();
77
private void fillCache() throws IOException {
78
while(input.incrementToken()) {
79
cache.add(captureState());
81
// capture final state
83
finalState = captureState();