1 package org.apache.lucene.index; 2 3 18 19 import java.io.ByteArrayOutputStream ; 20 import java.io.IOException ; 21 import java.util.Enumeration ; 22 import java.util.zip.Deflater ; 23 24 import org.apache.lucene.document.Document; 25 import org.apache.lucene.document.Field; 26 import org.apache.lucene.store.Directory; 27 import org.apache.lucene.store.IndexOutput; 28 29 final class FieldsWriter 30 { 31 static final byte FIELD_IS_TOKENIZED = 0x1; 32 static final byte FIELD_IS_BINARY = 0x2; 33 static final byte FIELD_IS_COMPRESSED = 0x4; 34 35 private FieldInfos fieldInfos; 36 37 private IndexOutput fieldsStream; 38 39 private IndexOutput indexStream; 40 41 FieldsWriter(Directory d, String segment, FieldInfos fn) throws IOException { 42 fieldInfos = fn; 43 fieldsStream = d.createOutput(segment + ".fdt"); 44 indexStream = d.createOutput(segment + ".fdx"); 45 } 46 47 final void close() throws IOException { 48 fieldsStream.close(); 49 indexStream.close(); 50 } 51 52 final void addDocument(Document doc) throws IOException { 53 indexStream.writeLong(fieldsStream.getFilePointer()); 54 55 int storedCount = 0; 56 Enumeration fields = doc.fields(); 57 while (fields.hasMoreElements()) { 58 Field field = (Field) fields.nextElement(); 59 if (field.isStored()) 60 storedCount++; 61 } 62 fieldsStream.writeVInt(storedCount); 63 64 fields = doc.fields(); 65 while (fields.hasMoreElements()) { 66 Field field = (Field) fields.nextElement(); 67 if (field.isStored()) { 68 fieldsStream.writeVInt(fieldInfos.fieldNumber(field.name())); 69 70 byte bits = 0; 71 if (field.isTokenized()) 72 bits |= FieldsWriter.FIELD_IS_TOKENIZED; 73 if (field.isBinary()) 74 bits |= FieldsWriter.FIELD_IS_BINARY; 75 if (field.isCompressed()) 76 bits |= FieldsWriter.FIELD_IS_COMPRESSED; 77 78 fieldsStream.writeByte(bits); 79 80 if (field.isCompressed()) { 81 byte[] data = null; 83 if (field.isBinary()) { 85 data = compress(field.binaryValue()); 86 } 87 else { 88 data = compress(field.stringValue().getBytes("UTF-8")); 89 } 90 final int len = data.length; 91 fieldsStream.writeVInt(len); 92 fieldsStream.writeBytes(data, len); 93 } 94 else { 95 if (field.isBinary()) { 97 byte[] data = field.binaryValue(); 98 final int len = data.length; 99 fieldsStream.writeVInt(len); 100 fieldsStream.writeBytes(data, len); 101 } 102 else { 103 fieldsStream.writeString(field.stringValue()); 104 } 105 } 106 } 107 } 108 } 109 110 private final byte[] compress (byte[] input) { 111 112 Deflater compressor = new Deflater (); 114 compressor.setLevel(Deflater.BEST_COMPRESSION); 115 116 compressor.setInput(input); 118 compressor.finish(); 119 120 126 ByteArrayOutputStream bos = new ByteArrayOutputStream (input.length); 127 128 byte[] buf = new byte[1024]; 130 while (!compressor.finished()) { 131 int count = compressor.deflate(buf); 132 bos.write(buf, 0, count); 133 } 134 135 compressor.end(); 136 137 return bos.toByteArray(); 139 } 140 } 141 | Popular Tags |