dbsearchmanager.java
来自「Jive是基于JSP/JAVA技术构架的一个大型BBS论坛系统,这是Jive论坛」· Java 代码 · 共 1,026 行 · 第 1/3 页
JAVA
1,026 行
if (body != null) { doc.add(Field.UnStored("body", body)); } doc.add(new Field("creationDate", DateField.dateToString(creationDate), false, true, false)); writer.addDocument(doc); // Close searcherReader since the index has changed. closeSearcherReader(); } /** * Deletes a message from the index. */ protected final void deleteMessagesFromIndex(long [] messages, IndexReader reader) throws IOException { if (messages == null || reader == null) { return; } Term term; for (int i=0; i<messages.length; i++) { term = new Term("messageID", Long.toString(messages[i])); reader.delete(term); } // Close searcherReader since the index has changed. closeSearcherReader(); } /** * Rebuilds the search index from scratch. It deletes the entire index * and word tables and then indexes every message up to the end time. */ private final void rebuildIndex(Date end) { // Attempt to acquire lock on index operations. try { if (!newIndexLock.attempt(10000)) { // We failed to acquire a lock after 10 seconds of waiting, // so give up. return; } } catch (InterruptedException ie) { return; } Directory newDirectory = null; String newDirName = null;; Connection con = null; PreparedStatement pstmt = null; String endDate = StringUtils.dateToMillis(end); IndexWriter writer = null; try { // Look for a new directory we can use. while (true) { String jiveHome = JiveGlobals.getJiveHome(); File mainDir = new File(jiveHome + File.separator + "search"); newDirName = StringUtils.randomString(8); File searchDir = new File(mainDir, newDirName); if (!searchDir.exists()) { searchDir.mkdir(); try { newDirectory = FSDirectory.getDirectory(searchDir, false); } catch (IOException ioe) { ioe.printStackTrace(); } break; } } writer = new IndexWriter(newDirectory, analyzer, true); con = ConnectionManager.getConnection(); // Get a count of the messages that will be added to index. pstmt = con.prepareStatement(MESSAGES_BEFORE_DATE_COUNT); pstmt.setString(1, endDate); ResultSet rs = pstmt.executeQuery(); rs.next(); // Set the total count so that we can keep track of percentage // complete. totalCount = rs.getInt(1); pstmt.close(); // Some JDBC drivers don't stream results, but read all records // returned by a query into memory. Most notably, the current // MySQL JDBC drivers have this problem. As a workaround, we read // message data in blocks (default 500). // First, get the highest messageID in the database. pstmt = con.prepareStatement(HIGHEST_MESSAGE_ID); rs = pstmt.executeQuery(); rs.next(); long maxID = rs.getLong(1); long sentinal = (long)(maxID / BLOCK_SIZE); pstmt.close(); // Now, use the messageIDs to select blocks of message data to add // to the index at a time. pstmt = con.prepareStatement(MESSAGES_BEFORE_DATE); for (int i = 0; i <= sentinal; i++) { pstmt.setLong(1, BLOCK_SIZE * i); pstmt.setLong(2, BLOCK_SIZE * (i + 1)); pstmt.setString(3, endDate); rs = pstmt.executeQuery(); while (rs.next()) { // Increment current count to track percentage complete. currentCount++; long messageID = rs.getLong(1); long userID = rs.getLong(2); long threadID = rs.getLong(3); long forumID = rs.getLong(4); String subject = rs.getString(5); String body = rs.getString(6); Date creationDate = new Date(Long.parseLong(rs.getString(7).trim())); addMessageToIndex(messageID, userID, threadID, forumID, subject, body, creationDate, writer); } rs.close(); } writer.optimize(); // Switch to the new directory for searching. searchDirectory = newDirectory; // Close searcherReader since the index has changed. closeSearcherReader(); // Change search directory to be the new one. JiveGlobals.setJiveProperty("search.directory", newDirName); } catch (Exception e) { e.printStackTrace(); } finally { try { pstmt.close(); } catch (Exception e) { e.printStackTrace(); } try { con.close(); } catch (Exception e) { e.printStackTrace(); } try { writer.close(); } catch (Exception e) { e.printStackTrace(); } // Reset counts currentCount = 0; totalCount = -1; // Release lock newIndexLock.release(); } } /** * Updates the index. It first deletes any messages in the index between * the start and end times, and then adds all messages to the index that * are between the start and end times. */ protected final void updateIndex(Date start, Date end) { // Attempt to acquire lock on index operations. try { if (!indexLock.attempt(10000)) { // We failed to acquire a lock after 10 seconds of waiting, // so give up. return; } } catch (InterruptedException ie) { return; } Connection con = null; PreparedStatement pstmt = null; IndexWriter writer = null; IndexReader reader = null; LongList messages = new LongList(); try { con = ConnectionManager.getConnection(); // For a clean update, we need to make sure that we first delete // any index entries that were made since we last updated. This // might happen if a process was calling indexMessage() between runs // of this method. For this reason, the two types of indexing (manual // and automatic) should not be intermixed. However, we still perform // this deletion to be safe. pstmt = con.prepareStatement(MESSAGE_IDS_SINCE_DATE); pstmt.setString(1, StringUtils.dateToMillis(start)); pstmt.setString(2, StringUtils.dateToMillis(end)); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { messages.add(rs.getLong(1)); } pstmt.close(); // Now, delete those messages reader = getReader(); deleteMessagesFromIndex(messages.toArray(), reader); // Get a count of the messages that will be added to index. pstmt = con.prepareStatement(MESSAGES_SINCE_DATE_COUNT); pstmt.setString(1, StringUtils.dateToMillis(start)); pstmt.setString(2, StringUtils.dateToMillis(end)); rs = pstmt.executeQuery(); rs.next(); // Set the total count so that we can keep track of percentage // complete. totalCount = rs.getInt(1); pstmt.close(); // Add the messages to the index. writer = getWriter(); pstmt = con.prepareStatement(MESSAGES_SINCE_DATE); pstmt.setString(1, StringUtils.dateToMillis(start)); pstmt.setString(2, StringUtils.dateToMillis(end)); rs = pstmt.executeQuery(); while (rs.next()) { // Increment current count to track percentage complete. currentCount++; long messageID = rs.getLong(1); long userID = rs.getLong(2); long threadID = rs.getLong(3); long forumID = rs.getLong(4); String subject = rs.getString(5); String body = rs.getString(6); Date creationDate = new Date(Long.parseLong(rs.getString(7).trim())); addMessageToIndex(messageID, userID, threadID, forumID, subject, body, creationDate, writer); } // Close searcherReader since the index has changed. closeSearcherReader(); } catch (Exception e) { e.printStackTrace(); } finally { try { pstmt.close(); } catch (Exception e) { e.printStackTrace(); } try { con.close(); } catch (Exception e) { e.printStackTrace(); } try { writer.close(); } catch (Exception e) { } try { reader.close(); } catch (Exception e) { } // Reset counts currentCount = 0; totalCount = -1; // Release lock indexLock.release(); } } /** * Returns a Lucene IndexWriter. The create param indicates whether an * existing index should be used if it's found there. */ private static IndexWriter getWriter() throws IOException { if (searchDirectory != null && IndexReader.indexExists(searchDirectory)) { return new IndexWriter(searchDirectory, analyzer, false); } else { return null; } } /** * Returns a Lucene IndexReader. */ static IndexReader getReader() throws IOException { if (searchDirectory != null && IndexReader.indexExists(searchDirectory)) { return IndexReader.open(searchDirectory); } else { return null; } } /** * Returns a Lucene Searcher that can be used to execute queries. Lucene * can handle index reading even while updates occur. However, in order * for index changes to be reflected in search results, the reader must * be re-opened whenever the modifiedDate changes.<p> * * The location of the index is the "search" subdirectory in [jiveHome]. If * jiveHome is not set correctly, this method will fail. * * @return a Searcher that can be used to execute queries. */ static Searcher getSearcher() throws IOException { synchronized (analyzer) { if (searcherReader == null) { if (searchDirectory != null && IndexReader.indexExists(searchDirectory)) { searcherReader = IndexReader.open(searchDirectory); searcher = new IndexSearcher(searcherReader); } else { return null; } } } return searcher; } /** * Closes the reader used by the searcher to indicate that a change to the index was made. * A new searcher will be opened the next time one is requested. * * @throws IOException if an error occurs while closing the reader. */ private static void closeSearcherReader() throws IOException { if (searcherReader != null) { try { searcherLock.acquireWriteLock(); searcherReader.close(); } finally { searcherReader = null; searcherLock.releaseWriteLock(); } } } /** * Performs indexing tasks using the Jive Task Engine. */ private class IndexTask implements Runnable { private boolean rebuildOperation; public IndexTask(boolean rebuildOperation) { this.rebuildOperation = rebuildOperation; // Do a rebuild if the index has never been built before. if (lastIndexed.getTime() == 0) { this.rebuildOperation = true; } } public void run() { Date now = new Date(); if (rebuildOperation) { rebuildIndex(now); } else { updateIndex(lastIndexed, now); } lastIndexed = now; // Save the last indexed time as a Jive property. JiveGlobals.setJiveProperty("search.lastIndexed", "" + now.getTime()); } }}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?