1 41 package com.mvnforum.search.post; 42 43 import java.io.IOException ; 44 import java.util.*; 45 46 import com.mvnforum.MVNForumConfig; 47 import com.mvnforum.db.DAOFactory; 48 import com.mvnforum.db.PostBean; 49 import net.myvietnam.mvncore.exception.DatabaseException; 50 import org.apache.commons.logging.Log; 51 import org.apache.commons.logging.LogFactory; 52 import org.apache.lucene.index.IndexWriter; 53 import org.apache.lucene.store.Directory; 54 55 58 public class RebuildPostIndexTask extends TimerTask 59 { 60 private static Log log = LogFactory.getLog(RebuildPostIndexTask.class); 61 62 public static final int POSTS_PER_FETCH = 200; 63 64 public static final int MERGE_FACTOR = 20; 65 66 private int maxPostID = 0; 67 68 private static boolean isRebuilding = false; 69 70 public static boolean isRebuilding() { 71 return isRebuilding; 72 } 73 74 77 RebuildPostIndexTask(int maxPostID) { 78 this.maxPostID = maxPostID; 79 } 80 81 84 public void run() { 85 isRebuilding = true; 86 long start = System.currentTimeMillis(); 87 88 Directory directory = null; 89 IndexWriter writer = null; 90 try { 91 directory = MVNForumConfig.getSearchPostIndexDir(); 92 writer = PostIndexer.getIndexWriter(directory, true); 93 writer.mergeFactor = MERGE_FACTOR; 94 if (maxPostID <= 0) { 98 maxPostID = DAOFactory.getPostDAO().getMaxPostID(); 99 } 100 int count = 0; 101 102 for (int fromID = 0; fromID <= maxPostID ; fromID += POSTS_PER_FETCH) { 103 int toID = fromID + POSTS_PER_FETCH - 1; 104 if (toID > maxPostID) { 105 toID = maxPostID; 106 } 107 Collection posts = DAOFactory.getPostDAO().getPosts_fromIDRange(fromID, toID); 108 109 for (Iterator iter = posts.iterator(); iter.hasNext(); ) { 110 PostBean post = (PostBean) iter.next(); 111 PostIndexer.doIndexPost(post, writer); 112 count++; 113 } 114 } 116 writer.optimize(); 117 log.info("Rebuilt index finished successfully! " + count + " post(s) indexed."); 118 } catch (DatabaseException ex) { 119 log.error("RebuildPostIndexTask.run : cannot get posts from database for indexing", ex); 120 } catch (Exception e) { 121 log.error("Error while rebuilding index", e); 122 } finally { 123 if (writer != null) { 124 try { 125 writer.close(); 126 } catch (IOException e) { 127 log.debug("Error closing Lucene IndexWriter", e); 128 } 129 } 130 if (directory != null) { 131 try { 132 directory.close(); 133 } catch (IOException e) { 134 log.debug("Cannot close directory.", e); 135 } 136 } 137 } 138 log.info("RebuildPostIndexTask took " + (System.currentTimeMillis() - start) + " ms"); 139 isRebuilding = false; 140 } 141 } 142 | Popular Tags |