import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.analysis.SimpleAnalyzer;
import java.io.StringReader;
import java.util.Enumeration;

/**
 * A class to compare the behaviour of stored versus
 * unstored Field objects within Documents.
 * @author lex_lawrence@hotmail.com
 */
 public class FieldTest
 {
 	public static void main(String[] args) throws Exception
 	{
 		/* Create one of each standard Field type */
 		Field keyword = Field.Keyword("keyword-name", "Keyword value");
 		Field stringText = Field.Text("stringtext-name", "String Text value");
 		Field readerText = Field.Text("readertext-name", new StringReader("Reader Text value"));
 		Field unIndexed = Field.UnIndexed("unindexed-name", "UnIndexed value");
 		Field unStored = Field.UnStored("unstored-name","UnStored value");
 		
 		/* Create a new Document */
 		Document doc = new Document();
 		doc.add(keyword);
 		doc.add(stringText);
 		doc.add(readerText);
 		doc.add(unIndexed);
 		doc.add(unStored);
 		System.out.println();
 		System.out.println("Newly created Document:");
		FieldTest.printDocFieldInfo(doc);
 		
 		/* Write Document to an index. */
 		IndexWriter iWriter = new IndexWriter("index", new SimpleAnalyzer(), true);
 		iWriter.addDocument(doc);
 		iWriter.close();
 		
 		doc = null;
 		
 		/* Read Document from index */
 		IndexReader iReader = IndexReader.open("index");
		TermDocs tDocs = iReader.termDocs();	//retrieve list of all terms in index
		tDocs.next();	//go to first term in list
		int docNum = tDocs.doc();	//get number of document of current term
		doc = iReader.document(docNum);
		
		System.out.println();
 		System.out.println("Document read from index:");
		FieldTest.printDocFieldInfo(doc);
		
		/* Now try to retrieve unstored Fields explicitly */
		System.out.println();
		System.out.println("Fields retrieved explicitly by name:");
		System.out.println("Document.getField(\"keyword-name\") = " + doc.getField("keyword-name"));
		System.out.println("Document.getField(\"stringtext-name\") = " + doc.getField("stringtext-name"));
		System.out.println("Document.getField(\"readertext-name\") = " + doc.getField("readertext-name"));
		System.out.println("Document.getField(\"unindexed-name\") = " + doc.getField("unindexed-name"));
		System.out.println("Document.getField(\"unstored-name\") = " + doc.getField("unstored-name"));
 		
 	}
 	
 	
 	/**
 	 * Print information on the Fields in a Document.
 	 */
 	public static void printDocFieldInfo(Document doc) {
 		
 		System.out.println();
 		System.out.println("Document.toString() :");
 		System.out.println(doc);
 		
 		System.out.println();
 		System.out.println("Retrieve Fields with Document.fields() :");
 		Enumeration fieldEnum = doc.fields();
 		while( fieldEnum.hasMoreElements() ) {
 			System.out.println(fieldEnum.nextElement());
 		}
 		
 	}
 	
 }