~slub.team/goobi-indexserver/3.x

« back to all changes in this revision

Viewing changes to solr/core/src/java/org/apache/solr/analysis/WordDelimiterFilterFactory.java

  • Committer: Sebastian Meyer
  • Date: 2012-08-03 09:12:40 UTC
  • Revision ID: sebastian.meyer@slub-dresden.de-20120803091240-x6861b0vabq1xror
Remove Lucene and Solr source code and add patches instead
Fix Bug #985487: Auto-suggestion for the search interface

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/**
2
 
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 
 * contributor license agreements.  See the NOTICE file distributed with
4
 
 * this work for additional information regarding copyright ownership.
5
 
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 
 * (the "License"); you may not use this file except in compliance with
7
 
 * the License.  You may obtain a copy of the License at
8
 
 *
9
 
 *     http://www.apache.org/licenses/LICENSE-2.0
10
 
 *
11
 
 * Unless required by applicable law or agreed to in writing, software
12
 
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 
 * See the License for the specific language governing permissions and
15
 
 * limitations under the License.
16
 
 */
17
 
 
18
 
package org.apache.solr.analysis;
19
 
 
20
 
import org.apache.lucene.analysis.TokenStream;
21
 
import org.apache.lucene.analysis.CharArraySet;
22
 
 
23
 
import org.apache.solr.util.plugin.ResourceLoaderAware;
24
 
import org.apache.solr.common.ResourceLoader;
25
 
import org.apache.solr.common.util.StrUtils;
26
 
 
27
 
import java.util.ArrayList;
28
 
import java.util.List;
29
 
import java.util.Map;
30
 
import java.util.SortedMap;
31
 
import java.util.TreeMap;
32
 
import java.util.regex.Matcher;
33
 
import java.util.regex.Pattern;
34
 
import java.io.IOException;
35
 
 
36
 
import static org.apache.solr.analysis.WordDelimiterFilter.*;
37
 
 
38
 
 
39
 
/**
40
 
 * Factory for WordDelimiterFilter.
41
 
 * <pre class="prettyprint" >
42
 
 * &lt;fieldType name="text_wd" class="solr.TextField" positionIncrementGap="100"&gt;
43
 
 *   &lt;analyzer&gt;
44
 
 *     &lt;tokenizer class="solr.WhitespaceTokenizerFactory"/&gt;
45
 
 *     &lt;filter class="solr.WordDelimiterFilterFactory" protected="protectedword.txt"
46
 
 *             preserveOriginal="0" splitOnNumerics="1" splitOnCaseChange="1"
47
 
 *             catenateWords="0" catenateNumbers="0" catenateAll="0"
48
 
 *             generateWordParts="1" generateNumberParts="1" stemEnglishPossessive="1"/&gt;
49
 
 *   &lt;/analyzer&gt;
50
 
 * &lt;/fieldType&gt;</pre> 
51
 
 * @version $Id: WordDelimiterFilterFactory.java 1166766 2011-09-08 15:52:10Z rmuir $
52
 
 */
53
 
public class WordDelimiterFilterFactory extends BaseTokenFilterFactory implements ResourceLoaderAware {
54
 
  public static final String PROTECTED_TOKENS = "protected";
55
 
  public static final String TYPES = "types";
56
 
  
57
 
  public void inform(ResourceLoader loader) {
58
 
    String wordFiles = args.get(PROTECTED_TOKENS);
59
 
    if (wordFiles != null) {  
60
 
      try {
61
 
        protectedWords = getWordSet(loader, wordFiles, false);
62
 
      } catch (IOException e) {
63
 
        throw new RuntimeException(e);
64
 
      }
65
 
    }
66
 
    String types = args.get(TYPES);
67
 
    if (types != null) {
68
 
      try {
69
 
        List<String> files = StrUtils.splitFileNames( types );
70
 
        List<String> wlist = new ArrayList<String>();
71
 
        for( String file : files ){
72
 
          List<String> lines = loader.getLines( file.trim() );
73
 
          wlist.addAll( lines );
74
 
        }
75
 
      typeTable = parseTypes(wlist);
76
 
      } catch (IOException e) {
77
 
        throw new RuntimeException(e);
78
 
      }
79
 
    }
80
 
  }
81
 
 
82
 
  private CharArraySet protectedWords = null;
83
 
  private int flags;
84
 
  byte[] typeTable = null;
85
 
 
86
 
  @Override
87
 
  public void init(Map<String, String> args) {
88
 
    super.init(args);
89
 
    if (getInt("generateWordParts", 1) != 0) {
90
 
      flags |= GENERATE_WORD_PARTS;
91
 
    }
92
 
    if (getInt("generateNumberParts", 1) != 0) {
93
 
      flags |= GENERATE_NUMBER_PARTS;
94
 
    }
95
 
    if (getInt("catenateWords", 0) != 0) {
96
 
      flags |= CATENATE_WORDS;
97
 
    }
98
 
    if (getInt("catenateNumbers", 0) != 0) {
99
 
      flags |= CATENATE_NUMBERS;
100
 
    }
101
 
    if (getInt("catenateAll", 0) != 0) {
102
 
      flags |= CATENATE_ALL;
103
 
    }
104
 
    if (getInt("splitOnCaseChange", 1) != 0) {
105
 
      flags |= SPLIT_ON_CASE_CHANGE;
106
 
    }
107
 
    if (getInt("splitOnNumerics", 1) != 0) {
108
 
      flags |= SPLIT_ON_NUMERICS;
109
 
    }
110
 
    if (getInt("preserveOriginal", 0) != 0) {
111
 
      flags |= PRESERVE_ORIGINAL;
112
 
    }
113
 
    if (getInt("stemEnglishPossessive", 1) != 0) {
114
 
      flags |= STEM_ENGLISH_POSSESSIVE;
115
 
    }
116
 
  }
117
 
 
118
 
  public WordDelimiterFilter create(TokenStream input) {
119
 
    return new WordDelimiterFilter(input, typeTable == null ? WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE : typeTable,
120
 
                                   flags, protectedWords);
121
 
  }
122
 
  
123
 
  // source => type
124
 
  private static Pattern typePattern = Pattern.compile( "(.*)\\s*=>\\s*(.*)\\s*$" );
125
 
  
126
 
  /** parses a list of MappingCharFilter style rules into a custom byte[] type table */
127
 
  private byte[] parseTypes(List<String> rules) {
128
 
    SortedMap<Character,Byte> typeMap = new TreeMap<Character,Byte>();
129
 
    for( String rule : rules ){
130
 
      Matcher m = typePattern.matcher(rule);
131
 
      if( !m.find() )
132
 
        throw new RuntimeException("Invalid Mapping Rule : [" + rule + "]");
133
 
      String lhs = parseString(m.group(1).trim());
134
 
      Byte rhs = parseType(m.group(2).trim());
135
 
      if (lhs.length() != 1)
136
 
        throw new RuntimeException("Invalid Mapping Rule : [" + rule + "]. Only a single character is allowed.");
137
 
      if (rhs == null)
138
 
        throw new RuntimeException("Invalid Mapping Rule : [" + rule + "]. Illegal type.");
139
 
      typeMap.put(lhs.charAt(0), rhs);
140
 
    }
141
 
    
142
 
    // ensure the table is always at least as big as DEFAULT_WORD_DELIM_TABLE for performance
143
 
    byte types[] = new byte[Math.max(typeMap.lastKey()+1, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE.length)];
144
 
    for (int i = 0; i < types.length; i++)
145
 
      types[i] = WordDelimiterIterator.getType(i);
146
 
    for (Map.Entry<Character,Byte> mapping : typeMap.entrySet())
147
 
      types[mapping.getKey()] = mapping.getValue();
148
 
    return types;
149
 
  }
150
 
  
151
 
  private Byte parseType(String s) {
152
 
    if (s.equals("LOWER"))
153
 
      return LOWER;
154
 
    else if (s.equals("UPPER"))
155
 
      return UPPER;
156
 
    else if (s.equals("ALPHA"))
157
 
      return ALPHA;
158
 
    else if (s.equals("DIGIT"))
159
 
      return DIGIT;
160
 
    else if (s.equals("ALPHANUM"))
161
 
      return ALPHANUM;
162
 
    else if (s.equals("SUBWORD_DELIM"))
163
 
      return SUBWORD_DELIM;
164
 
    else
165
 
      return null;
166
 
  }
167
 
  
168
 
  char[] out = new char[256];
169
 
  
170
 
  private String parseString(String s){
171
 
    int readPos = 0;
172
 
    int len = s.length();
173
 
    int writePos = 0;
174
 
    while( readPos < len ){
175
 
      char c = s.charAt( readPos++ );
176
 
      if( c == '\\' ){
177
 
        if( readPos >= len )
178
 
          throw new RuntimeException( "Invalid escaped char in [" + s + "]" );
179
 
        c = s.charAt( readPos++ );
180
 
        switch( c ) {
181
 
          case '\\' : c = '\\'; break;
182
 
          case 'n' : c = '\n'; break;
183
 
          case 't' : c = '\t'; break;
184
 
          case 'r' : c = '\r'; break;
185
 
          case 'b' : c = '\b'; break;
186
 
          case 'f' : c = '\f'; break;
187
 
          case 'u' :
188
 
            if( readPos + 3 >= len )
189
 
              throw new RuntimeException( "Invalid escaped char in [" + s + "]" );
190
 
            c = (char)Integer.parseInt( s.substring( readPos, readPos + 4 ), 16 );
191
 
            readPos += 4;
192
 
            break;
193
 
        }
194
 
      }
195
 
      out[writePos++] = c;
196
 
    }
197
 
    return new String( out, 0, writePos );
198
 
  }
199
 
}