此處添加一個(gè)logmanager類
package net.skycity.blog;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.sf.hibernate.Criteria;
import net.sf.hibernate.Session;
import net.sf.hibernate.expression.Expression;
import net.sf.hibernate.expression.Order;
import net.skycity.model.LogForm;
import net.skycity.search.SearchEnginePlugIn;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.FSDirectory;
public class LogManager extends SearchEnginePlugIn {
?
?public static List searchFor(String logTypeId,String state,String author,String query) throws Exception{
??List logs = new ArrayList();
??????? List ids = searchFor(1,logTypeId,query,0,-1);
??????? if(ids.size()>0){
??????? ?Session ssn=ManagerBase.getSession();
??????????? Criteria crit = ssn.createCriteria(LogForm.class).add(Expression.eq("siteId", "1"));
??????????? crit = crit.add(Expression.in("logId",ids));
??? ??String orderField = "submitTime";
??? ??crit = crit.addOrder(Order.desc(orderField));
??????????? logs = crit.list();
??????????? ssn.close();
??????? }
??return logs;
?}
?
?public static List searchFor(String logTypeId,String state,String author) throws Exception {
??Session ssn=ManagerBase.getSession();
??List list = null;
??try{
???Criteria crit=ssn.createCriteria(LogForm.class).add(Expression.eq("author",author));
???if(!logTypeId.equals("0"))
????crit.add(Expression.eq("logTypeId",logTypeId));
???if(!StringUtils.isEmpty(state))
????crit.add(Expression.eq("state",state));
???list=crit.list();
??}finally{
???ssn.close();
??}???
??return list;
?}
?
?public static List searchFor(int site, String logTypeId, String word, int from, int count) throws IOException, ParseException {
??List logs = new ArrayList();
??//從文件目錄中
??FSDirectory searchDirectory = FSDirectory.getDirectory(SearchEnginePlugIn.getLogIndexPath(), false);
??IndexReader reader = IndexReader.open(searchDirectory);
??IndexSearcher searcher = new IndexSearcher(reader);
??if (searcher == null) return logs;
??
??if(!StringUtils.isEmpty(word)){
???BooleanQuery comboQuery = new BooleanQuery();
???
???Query query1 = QueryParser.parse(word,"logTitle",new StandardAnalyzer());
???comboQuery.add(query1, false, false);
???Query query2 = QueryParser.parse(word,"content",new StandardAnalyzer());
???comboQuery.add(query2, false, false);
???
???Hits hits = searcher.search(comboQuery);
???
???int numResults = hits.length();
???for (int i = 0; i < numResults; i++) {
????if (count > 0 && logs.size() >= count) break;
?????? if (i < from) continue;
???????????? logs.add(new Integer(((Document) hits.doc(i)).get("logId")));
???}
??}
??reader.close();
??return logs;
?}
?
?public static void delLog(int logId) throws Exception{
??Session ssn=ManagerBase.getSession();
??LogForm log=(LogForm) ssn.load(LogForm.class,String.valueOf(logId));
??ssn.delete(log);
??delLogIndex(logId);
?}
?
?public static int createLogIndex(Object obj) throws Exception{
??????? LogForm log = (LogForm)obj;??????????????
??????? Document doc = new Document();
??????? doc.add(Field.Keyword("logId", String.valueOf(log.getLogId())));
??????? doc.add(new Field("author", log.getAuthor(),false,true,false));
??????? doc.add(new Field("siteId", log.getSiteId(),false,true,false));
??????? doc.add(new Field("logTypeId",log.getLogTypeId(),false,true, false));
??????? doc.add(Field.UnStored("logTitle", StringUtils.deleteWhitespace(log.getLogTitle())));
??????? doc.add(Field.UnStored("content", log.getContent()));
??????? doc.add(new Field("submitTime", log.getSubmitTime(),false,true,false));
??IndexWriter writer = getLogIndexWriter();
??try {
????? writer.addDocument(doc);
????? writer.optimize();
??}finally {
????? writer.close();
??}
??????? return 1;
??? }
?
?public static int createAllLogIndex() throws Exception{
??String logPath=getLogIndexPath();
??File file=new File(logPath);
??delDirectory(file);
??Session ssn=ManagerBase.getSession();
??String hql="from "+LogForm.class.getName();
??net.sf.hibernate.Query query=ssn.createQuery(hql);
??List logs = query.list();
??IndexWriter writer = getLogIndexWriter();
??int logCount=0;
??for(int i=0;i<logs.size();i++){
???Document doc = new Document();
??????? ?LogForm log = (LogForm)logs.get(i);
???????? doc.add(Field.Keyword("logId", String.valueOf(log.getLogId())));
???????? doc.add(new Field("author", log.getAuthor(),false,true,false));
???????? doc.add(new Field("siteId", log.getSiteId(),false,true,false));
???????? doc.add(new Field("logTypeId",log.getLogTypeId(),false,true, false));
???????? doc.add(Field.UnStored("logTitle", StringUtils.deleteWhitespace(log.getLogTitle())));
???????? doc.add(Field.UnStored("content", log.getContent()));
???????? doc.add(new Field("submitTime", log.getSubmitTime(),false,true,false));
???????? logCount++;
???????? writer.addDocument(doc);
??}
??writer.optimize();
??writer.close();
??System.out.println("建立索引數(shù)目:"+logCount);
??????? return logCount;
??? }
?public static int delLogIndex(int logId) throws Exception{
??IndexReader reader = IndexReader.open(getLogIndexPath());
??if (reader == null)
???return 0;
??int dc = 0;
??try {
???Term logIdTerm;
???logIdTerm = new Term("logId", Integer.toString(logId));
???try {
????dc += reader.delete(logIdTerm);
???}catch (Exception e) {}
??} finally {
???try {
????reader.close();
???} catch (Exception e) {}
??}
??return dc;
?}
?/**重建索引、刪除索引目錄下的所有文件
???? *
???? */
??? public static void delDirectory(File file) throws IOException{
??? ?if((file == null) || !file.isDirectory()){
??? ??throw new IllegalArgumentException(file+"不是一個(gè)目錄.");
??? ?}
??? ?File[] entries = file.listFiles();
??? ?int sz = entries.length;
??? ?for(int i=0;i<sz;i++) {
??? ??if(entries[i].isDirectory()) {
??? ????delDirectory(entries[i]);
??? ??}else{
??? ???System.out.println(entries[i].getName());
??? ???System.out.println(entries[i].getAbsolutePath());
??? ???entries[i].delete();
??? ??}
??? ?}
??? ?file.delete();
??? }
}
程序運(yùn)行時(shí)調(diào)用createAllLogIndex()則會(huì)創(chuàng)建所有的索引
現(xiàn)在實(shí)現(xiàn)jsp添加一個(gè)日志來(lái)新增一個(gè)索引:
<%@ page contentType="text/html;charset=GBK"%>
<style type="text/css">
body {
?color: #333333;
?font-size: 11px;
?font-family: Tahoma, Verdana, sans-serif, "宋體";
?margin: 0px;
?padding: 0px;
?background-position: center top;
}
table {font: 12px Verdana, Tahoma, sans-serif, "宋體";}
</style>
<body>
<table cellspacing="0" cellpadding="2" width="100%">
? <tr>
??? <td>
????? <table width='100%' border='0' cellspacing='1' cellpadding='2'>
??????? <tr>
????????? <td align="left"><b><font color="#000000">新增日志:</font></b></td>
??????? </tr>
????? </table>
????? <table width="100%" border="0" cellspacing="1" cellpadding="2">
???? <form action="addLog.do" name="log" method="post">
??? <tr>
??????????? <td align="center">日志標(biāo)題</td>
??????????? <td><input type="text" name="logTitle"/><font color="#FF0000"></td>
????????? </tr>
????????? <tr bgcolor="#f8f8f8">
??????????? <td align="center">文章分類</td>
??????????? <td>
????????????? <select name="logTypeId">
??????????? ?<option value="1">JAVA</option>
??????????? ?<option value="2">AJAX</option>
????????????? ?<option value="3">STRUTS</option>
?? ??? </select>
?? ??</td>
????????? </tr>
??? <tr bgcolor="#f8f8f8">
??????????? <td align="center">文章類型</td>
??????????? <td>
??????????? ?<input type="text" name="comeForm">
??????????? ?<a onclick="comeForm.value='原創(chuàng)'">原創(chuàng)</a>
??????????? ?<a onclick="comeForm.value='轉(zhuǎn)載'">轉(zhuǎn)載</a>
??????????? </td>
????????? </tr>
????????? <tr bgcolor="#f8f8f8">
??????????? <td align="center">文章?tīng)顟B(tài)</td>
??????????? <td>
??????????? ?<select name="state">
??????????? ??<option value="0">公開(kāi)</option>
??????????? ??<option value="1">草稿</option>
??????????? ??<option value="2">已刪除</option>
?? ??? </select>
??????????? </td>
????????? </tr>
????????? <tr bgcolor="#f8f8f8">
??????????? <td valign="top" align="center">內(nèi) 容</td>
??????????? <td rowspan="2">
??????????? ?<textarea cols="50" rows="10" name="content"></textarea>
??????????? ?<font color="#FF0000">*</font>
??????????? </td>
????????? </tr>
????????? <tr bgcolor="#f8f8f8">
??????????? <td align="center"> </td>
????????? </tr>
????????? <tr bgcolor="#f8f8f8">
??????????? <td align="center">評(píng) 論</td>
??????????? <td><input type="radio" name="canComment" value="0">不允許<input type="radio" name="canComment" value="1" checked>允許</td>
????????? </tr>
????????? <tr bgcolor="#f8f8f8">
??????????? <td colspan="2" height="40" align="center">
??????????? ?<input type="button" class="button" name="eventSubmit_addLog" onclick="CheckForm()" value="發(fā)表"/>
??????????? ?<input type="reset" class="button" name="btn_reset" value="重填"/>
?????????? ?</td>
????????? </tr>
?????????
???? ?</form>
????? </table></td>
? </tr>
</table>
</body>
<script language="javascript">
function CheckForm()
{
?with(document.log){
??if(logTitle.value==""){
???alert('日志標(biāo)題不能為空');
???logTitle.focus();
???return false;
??}
??if(content.value==""){
???alert('日志內(nèi)容不能為空');
???content.focus();
???return false;
??}
??submit();
?}
}
</script>
form的addLog.do在struts-config.xml中如下定義
<action path="/addLog" scope="request" name="LogForm" validate="false" type="net.skycity.action.LogAction" input="/index.jsp"/>
action的model層上面已經(jīng)介紹過(guò)了,實(shí)現(xiàn)添加文檔及索引的是LogAction
package net.skycity.action;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.hibernate.Session;
import net.skycity.blog.Globals;
import net.skycity.blog.LogManager;
import net.skycity.blog.ManagerBase;
import net.skycity.model.LogForm;
import net.skycity.util.WellsoonUtil;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class LogAction extends Action {
?public ActionForward execute(ActionMapping mapping,
??????????? ActionForm form, HttpServletRequest request,
??????????? HttpServletResponse response) throws Exception
??? {
??? ?LogForm log=(LogForm)form;
??? ?Session ssn=ManagerBase.getSession();
??try{
???log.setAuthor("admin");???//這里為了簡(jiǎn)便,都取了默認(rèn)值
???log.setSiteId("1");
???log.setLogTitle(WellsoonUtil.transfer(log.getLogTitle()));
???log.setComeForm(WellsoonUtil.transfer(log.getComeForm()));
???log.setSubmitTime(Globals.FORMAT_DT.format(new Date()));
???log.setContent(WellsoonUtil.transfer(log.getContent()));
???ssn.save(log);
???LogManager.createLogIndex(log);
??}finally{
???ManagerBase.commitSession(ssn, true);
??}
??? ?return mapping.findForward("success");
??? }
}
??重點(diǎn)是:ssn.save(log);?LogManager.createLogIndex(log);前一句,將提交的數(shù)據(jù)保存到數(shù)據(jù)庫(kù),后一句將提交的數(shù)據(jù)增加到索引中
通過(guò)這些程序,索引文件就已經(jīng)創(chuàng)建了
Lyyb2001