pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / facet / src / test / org / apache / lucene / facet / search / CategoryListIteratorTest.java
1 package org.apache.lucene.facet.search;
2
3 import java.io.IOException;
4 import java.io.Reader;
5 import java.util.HashSet;
6 import java.util.Set;
7
8 import org.apache.lucene.analysis.Analyzer;
9 import org.apache.lucene.analysis.MockAnalyzer;
10 import org.apache.lucene.analysis.MockTokenizer;
11 import org.apache.lucene.analysis.TokenStream;
12 import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
13 import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
14 import org.apache.lucene.document.Document;
15 import org.apache.lucene.document.Field;
16 import org.apache.lucene.document.Field.Index;
17 import org.apache.lucene.document.Field.Store;
18 import org.apache.lucene.index.IndexReader;
19 import org.apache.lucene.index.Payload;
20 import org.apache.lucene.index.RandomIndexWriter;
21 import org.apache.lucene.index.Term;
22 import org.apache.lucene.store.Directory;
23 import org.junit.Test;
24
25 import org.apache.lucene.util.LuceneTestCase;
26 import org.apache.lucene.facet.search.CategoryListIterator;
27 import org.apache.lucene.facet.search.PayloadIntDecodingIterator;
28 import org.apache.lucene.util.UnsafeByteArrayOutputStream;
29 import org.apache.lucene.util.encoding.DGapIntEncoder;
30 import org.apache.lucene.util.encoding.IntEncoder;
31 import org.apache.lucene.util.encoding.SortingIntEncoder;
32 import org.apache.lucene.util.encoding.UniqueValuesIntEncoder;
33 import org.apache.lucene.util.encoding.VInt8IntEncoder;
34
35 /**
36  * Licensed to the Apache Software Foundation (ASF) under one or more
37  * contributor license agreements.  See the NOTICE file distributed with
38  * this work for additional information regarding copyright ownership.
39  * The ASF licenses this file to You under the Apache License, Version 2.0
40  * (the "License"); you may not use this file except in compliance with
41  * the License.  You may obtain a copy of the License at
42  *
43  *     http://www.apache.org/licenses/LICENSE-2.0
44  *
45  * Unless required by applicable law or agreed to in writing, software
46  * distributed under the License is distributed on an "AS IS" BASIS,
47  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
48  * See the License for the specific language governing permissions and
49  * limitations under the License.
50  */
51
52 public class CategoryListIteratorTest extends LuceneTestCase {
53
54   private static final class DataTokenStream extends TokenStream {
55
56     private int idx;
57     private PayloadAttribute payload = addAttribute(PayloadAttribute.class);
58     private byte[] buf = new byte[20];
59     UnsafeByteArrayOutputStream ubaos = new UnsafeByteArrayOutputStream(buf);
60     IntEncoder encoder;
61     private boolean exhausted = false;
62     private CharTermAttribute term = addAttribute(CharTermAttribute.class);
63
64     public DataTokenStream(String text, IntEncoder encoder) throws IOException {
65       this.encoder = encoder;
66       term.setEmpty().append(text);
67     }
68
69     public void setIdx(int idx) {
70       this.idx = idx;
71       exhausted = false;
72     }
73
74     @Override
75     public boolean incrementToken() throws IOException {
76       if (exhausted) {
77         return false;
78       }
79
80       int[] values = data[idx];
81       ubaos.reInit(buf);
82       encoder.reInit(ubaos);
83       for (int val : values) {
84         encoder.encode(val);
85       }
86       encoder.close();
87       payload.setPayload(new Payload(buf, 0, ubaos.length()));
88
89       exhausted = true;
90       return true;
91     }
92
93   }
94
95   static final int[][] data = new int[][] {
96     new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 1, 3 }, new int[] { 1, 2, 3, 4 },
97   };
98
99   @Test
100   public void testPayloadIntDecodingIterator() throws Exception {
101     Directory dir = newDirectory();
102     DataTokenStream dts = new DataTokenStream("1",new SortingIntEncoder(
103         new UniqueValuesIntEncoder(new DGapIntEncoder(new VInt8IntEncoder()))));
104     RandomIndexWriter writer = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, 
105         new MockAnalyzer(random, MockTokenizer.KEYWORD, false)).setMergePolicy(newLogMergePolicy()));
106     for (int i = 0; i < data.length; i++) {
107       dts.setIdx(i);
108       Document doc = new Document();
109       doc.add(new Field("f", dts));
110       writer.addDocument(doc);
111     }
112     IndexReader reader = writer.getReader();
113     writer.close();
114
115     CategoryListIterator cli = new PayloadIntDecodingIterator(reader, new Term(
116         "f","1"), dts.encoder.createMatchingDecoder());
117     cli.init();
118     int totalCategories = 0;
119     for (int i = 0; i < data.length; i++) {
120       Set<Integer> values = new HashSet<Integer>();
121       for (int j = 0; j < data[i].length; j++) {
122         values.add(data[i][j]);
123       }
124       cli.skipTo(i);
125       long cat;
126       while ((cat = cli.nextCategory()) < Integer.MAX_VALUE) {
127         assertTrue("expected category not found: " + cat, values.contains((int) cat));
128         totalCategories ++;
129       }
130     }
131     assertEquals("Missing categories!",10,totalCategories);
132     reader.close();
133     dir.close();
134   }
135
136   /**
137    * Test that a document with no payloads does not confuse the payload decoder.
138    */
139   @Test
140   public void testPayloadIteratorWithInvalidDoc() throws Exception {
141     Directory dir = newDirectory();
142     DataTokenStream dts = new DataTokenStream("1",new SortingIntEncoder(
143         new UniqueValuesIntEncoder(new DGapIntEncoder(new VInt8IntEncoder()))));
144     // this test requires that no payloads ever be randomly present!
145     final Analyzer noPayloadsAnalyzer = new Analyzer() {
146       @Override
147       public TokenStream tokenStream(String fieldName, Reader reader) {
148         return new MockTokenizer(reader, MockTokenizer.KEYWORD, false);
149       }
150     };
151     // NOTE: test is wired to LogMP... because test relies on certain docids having payloads
152     RandomIndexWriter writer = new RandomIndexWriter(random, dir, 
153         newIndexWriterConfig(TEST_VERSION_CURRENT, noPayloadsAnalyzer).setMergePolicy(newLogMergePolicy()));
154     for (int i = 0; i < data.length; i++) {
155       Document doc = new Document();
156       if (i == 0) {
157         dts.setIdx(i);
158         doc.add(new Field("f", dts)); // only doc 0 has payloads!
159       } else {
160         doc.add(new Field("f", "1", Store.NO, Index.ANALYZED));
161       }
162       writer.addDocument(doc);
163       writer.commit();
164     }
165
166     IndexReader reader = writer.getReader();
167     writer.close();
168
169     CategoryListIterator cli = new PayloadIntDecodingIterator(reader, new Term(
170         "f","1"), dts.encoder.createMatchingDecoder());
171     assertTrue("Failed to initialize payload iterator", cli.init());
172     int totalCats = 0;
173     for (int i = 0; i < data.length; i++) {
174       // doc no. i
175       Set<Integer> values = new HashSet<Integer>();
176       for (int j = 0; j < data[i].length; j++) {
177         values.add(data[i][j]);
178       }
179       boolean hasDoc = cli.skipTo(i);
180       if (hasDoc) {
181         assertTrue("Document " + i + " must not have a payload!", i == 0);
182         long cat;
183         while ((cat = cli.nextCategory()) < Integer.MAX_VALUE) {
184           assertTrue("expected category not found: " + cat, values.contains((int) cat));
185           ++totalCats;
186         }
187       } else {
188         assertFalse("Document " + i + " must have a payload!", i == 0);
189       }
190
191     }
192     assertEquals("Wrong number of total categories!", 2, totalCats);
193
194     reader.close();
195     dir.close();
196   }
197
198 }