1 package com.atlassian.bonnie.search;
2
3 import com.atlassian.bonnie.ILuceneConnection;
4 import com.atlassian.bonnie.Indexer;
5 import com.atlassian.bonnie.Searchable;
6 import org.apache.lucene.index.IndexReader;
7 import org.apache.lucene.index.IndexWriter;
8 import org.apache.lucene.index.Term;
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11 import org.slf4j.MDC;
12
13 import java.io.IOException;
14
15
16
17
18 public class LuceneIndexer implements Indexer
19 {
20 private static final Logger log = LoggerFactory.getLogger(LuceneIndexer.class);
21
22 private ILuceneConnection luceneConnection;
23 private DocumentBuilder documentBuilder;
24
25 public void index(final Searchable obj)
26 {
27 if (!obj.isIndexable())
28 {
29 return;
30 }
31
32 unIndex(obj);
33
34 luceneConnection.withWriter(new ILuceneConnection.WriterAction()
35 {
36 public void perform(IndexWriter indexWriter) throws IOException
37 {
38 try
39 {
40 MDC.put("Indexing", obj.toString());
41 indexWriter.addDocument(documentBuilder.getDocument(obj));
42 }
43 finally
44 {
45 MDC.remove("Indexing");
46 }
47 }
48 });
49 }
50
51 public void unIndex(final Searchable obj)
52 {
53 luceneConnection.withReaderAndDeletes(new ILuceneConnection.ReaderAction()
54 {
55 public Object perform(IndexReader indexReader) throws IOException
56 {
57 try
58 {
59 MDC.put("Unindexing", obj.toString());
60 Term t = new Term(BaseDocumentBuilder.FieldName.HANDLE, documentBuilder.getHandle(obj).toString());
61 indexReader.deleteDocuments(t);
62 return null;
63 }
64 finally
65 {
66 MDC.remove("Unindexing");
67 }
68 }
69 });
70 }
71
72 public void reIndex(Searchable obj)
73 {
74 unIndex(obj);
75 index(obj);
76 }
77
78 public void unIndexAll()
79 {
80 luceneConnection.truncateIndex();
81 }
82
83 public void setLuceneConnection(ILuceneConnection luceneConnection)
84 {
85 this.luceneConnection = luceneConnection;
86 }
87
88 public void setDocumentBuilder(DocumentBuilder documentBuilder)
89 {
90 this.documentBuilder = documentBuilder;
91 }
92 }