1 17 package org.apache.servicemix.jbi.audit.lucene; 18 19 import java.io.File ; 20 import java.io.IOException ; 21 22 import org.apache.lucene.analysis.SimpleAnalyzer; 23 import org.apache.lucene.document.Document; 24 import org.apache.lucene.index.IndexReader; 25 import org.apache.lucene.index.IndexWriter; 26 import org.apache.lucene.index.Term; 27 import org.apache.lucene.search.IndexSearcher; 28 import org.apache.lucene.store.Directory; 29 import org.apache.lucene.store.FSDirectory; 30 36 37 public class LuceneIndexer { 38 protected Directory directory; 39 private File segmentFile; 40 41 public LuceneIndexer() { 42 } 43 44 public Directory getDirectory() { 45 return directory; 46 } 47 48 public void setDirectory(Directory directory) { 49 this.directory = directory; 50 } 51 52 public void setDirectoryName(File directoryName) throws IOException { 53 this.segmentFile = new File (directoryName,"segments"); 54 this.directory = FSDirectory.getDirectory(directoryName.toString(),!this.segmentFile.exists()); 55 } 56 57 60 protected void remove(String id) throws IOException { 61 synchronized (directory) { 62 IndexReader ir = IndexReader.open(directory); 63 try{ 64 ir.delete(new Term("org.apache.servicemix.exchangeid", id)); 65 } 66 finally{ 67 ir.close(); 68 } 69 } 70 } 71 72 protected void remove(String [] ids) throws IOException { 73 if (ids != null && ids.length > 0) { 74 synchronized (directory) { 75 IndexReader ir = IndexReader.open(directory); 76 try{ 77 for (int i=0;i<ids.length;i++) 78 ir.delete(new Term("org.apache.servicemix.exchangeid", ids[i])); 79 } 80 finally{ 81 ir.close(); 82 } 83 } 84 } 85 } 86 87 90 public void add(Document lucDoc, String id) throws IOException { 91 synchronized (directory) { 92 IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), !segmentFile.exists()); 93 try{ 94 writer.addDocument(lucDoc); 95 } 96 finally{ 97 writer.close(); 98 } 99 } 100 } 101 102 105 public void update(Document lucDoc, String id) throws IOException { 106 remove(id); 107 add(lucDoc,id); 108 } 109 110 111 public Object search (LuceneCallback lc) throws IOException { 112 synchronized (directory) { 113 IndexReader ir = IndexReader.open(directory); 114 IndexSearcher is = new IndexSearcher(ir); 115 try{ 116 return lc.doCallback(is); 117 } 118 finally{ 119 is.close(); 120 ir.close(); 121 } 122 } 123 } 124 } | Popular Tags |