01: package org.compass.core.lucene.engine;
02:
03: import java.io.IOException;
04: import java.io.Reader;
05: import java.io.StringReader;
06: import java.util.ArrayList;
07:
08: import org.apache.lucene.analysis.Analyzer;
09: import org.apache.lucene.analysis.Token;
10: import org.apache.lucene.analysis.TokenStream;
11: import org.compass.core.CompassToken;
12: import org.compass.core.Resource;
13: import org.compass.core.engine.SearchEngineAnalyzerHelper;
14: import org.compass.core.engine.SearchEngineException;
15: import org.compass.core.lucene.LuceneToken;
16: import org.compass.core.lucene.engine.analyzer.LuceneAnalyzerManager;
17:
18: /**
19: * @author kimchy
20: */
21: public class LuceneSearchEngineAnalyzerHelper implements
22: SearchEngineAnalyzerHelper {
23:
24: private LuceneAnalyzerManager analyzerManager;
25:
26: private Analyzer analyzer;
27:
28: public LuceneSearchEngineAnalyzerHelper(
29: LuceneSearchEngine searchEngine) {
30: this .analyzerManager = searchEngine.getSearchEngineFactory()
31: .getAnalyzerManager();
32: this .analyzer = analyzerManager.getDefaultAnalyzer();
33: }
34:
35: public SearchEngineAnalyzerHelper setAnalyzer(String analyzerName) {
36: this .analyzer = analyzerManager
37: .getAnalyzerMustExist(analyzerName);
38: return this ;
39: }
40:
41: public SearchEngineAnalyzerHelper setAnalyzer(Resource resource)
42: throws SearchEngineException {
43: this .analyzer = analyzerManager.getAnalyzerByResource(resource);
44: return this ;
45: }
46:
47: public SearchEngineAnalyzerHelper setAnalyzerByAlias(String alias)
48: throws SearchEngineException {
49: this .analyzer = analyzerManager
50: .getAnalyzerByAliasMustExists(alias);
51: return this ;
52: }
53:
54: public CompassToken analyzeSingle(String text)
55: throws SearchEngineException {
56: CompassToken[] tokens = analyze(text);
57: if (tokens == null || tokens.length == 0) {
58: return null;
59: }
60: return tokens[0];
61: }
62:
63: public CompassToken[] analyze(String text) {
64: return analyze(new StringReader(text));
65: }
66:
67: public CompassToken[] analyze(String propertyName, String text)
68: throws SearchEngineException {
69: return analyze(propertyName, new StringReader(text));
70: }
71:
72: public CompassToken[] analyze(Reader textReader)
73: throws SearchEngineException {
74: return analyze(null, textReader);
75: }
76:
77: public CompassToken[] analyze(String propertyName, Reader textReader)
78: throws SearchEngineException {
79: try {
80: TokenStream tokenStream = analyzer.tokenStream(
81: propertyName, textReader);
82: ArrayList tokenList = new ArrayList();
83: while (true) {
84: Token token = tokenStream.next();
85: if (token == null)
86: break;
87: tokenList.add(new LuceneToken(token));
88: }
89:
90: return (CompassToken[]) tokenList
91: .toArray(new CompassToken[tokenList.size()]);
92: } catch (IOException e) {
93: throw new SearchEngineException(
94: "Failed to iterate token stream from analyzer ["
95: + analyzer + "]");
96: }
97: }
98: }
|