您的位置:首页 > 其它

对天乙社区bbscs8实现的详细分析七

2008-07-14 11:04 288 查看
此文为转载:http://www.diybl.com/course/1_web/webjs/2007113/82989.html

我们仍然将分析处于service包中,首分析下上次没有分析的ForumArchiveService:(它只有一个方法)
public interface ForumArchivesService {
public void createForumArchives() throws BbscsException;
}
看applicationContext.xml中:

/**

History

而以前讲过的forumMain:

Main

对于这个forumHistoryDAO,其实它只不过是一个ForumHibernateDAO的引用而已,只不过加了个History构造参数!
public ForumHibernateDAO(String flag) {
super();
this.flag = flag; //flag不是main了,而是History了!!!那后面的
private String getObjName() {
return "Forum" + this.flag;//ForumHistory!
}

private Class getForumClass() {
return Constant.FORUM_CLASS_MAP.get(this.flag); //ForumHistory.class!
}
*/

/**com.laoer.bbscs.dao.jdbc.ForumArchivesJDBCDAO,其实这个JDBC操作由
this.getJdbcTemplate().update(sql, o);完成的!!!注意需导入org.springframework.jdbc.core.support.JdbcDaoSupport;
public void saveForumArchives(long bid, Forum f) {
String sql = "insert into bbscs_forumarchives_"
+ (bid % 10)
+ " (ParentID, MainID, BoardID, BoardName, ReNum, Face, UserID, UserName, NickName, Title, Detail, Sign, ArtSize, Click, PostTime, LastTime, IPAddress, IsNew, Elite, EliteID, Agree, BeAgainst, CanNotDel, CanNotRe, Commend, DelSign, DelUserID, DelUserName, DelTime, DelIP, Amend, DoEliteName, DoEliteTime, HaveAttachFile, AttachFileName, LastPostUserName, LastPostTitle, LastPostNickName, IsTop, IsLock, Auditing, AuditingAttachFile, IsVote, IsHidden, IsHiddenValue, EditType, QuoteText, QuoteEditType, PostType, TitleColor, UserBlog, IndexStatus, EmailInform, MsgInform, VoteID, TagID, TagName, IsGuest, PreviewAttach, ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; //由bid决定写入10个表中的其中一个!!!
Object[] o = new Object[] { f.getParentID(), f.getMainID(), f.getBoardID(), f.getBoardName(), f.getReNum(),
f.getFace(), f.getUserID(), f.getUserName(), f.getNickName(), f.getTitle(), f.getDetail(), f.getSign(),
f.getArtSize(),....};
this.getJdbcTemplate().update(sql, o);
}

private String attachFileName2String(List attachFileName) { //将List--->String
String text = "";
if (attachFileName != null) {
for (int i = 0; i < attachFileName.size(); i++) {
String fileName = (String) attachFileName.get(i);
text = text + fileName + ",";
}
if (text.endsWith(",")) {
text = text.substring(0, (text.length() - 1));
}
}
return text;
}
*/

在其实现类ForumArchiveServiceImp中注入了forumHistoryDAO,boardService,tempConfiguration,forumConfig,SysConfig等其它服务和DAO...其中,tempConfiguration是一个freemarker.template下面的Configuration对象.
public void createForumArchives() throws BbscsException {
for (int y = 12; y >= 3; y--) {
Calendar cld = Calendar.getInstance();
cld.set(Calendar.HOUR_OF_DAY, 0);
cld.set(Calendar.MINUTE, 0);
cld.set(Calendar.SECOND, 0);
cld.set(Calendar.MILLISECOND, 0);
cld.add(Calendar.MONTH, -y);//三个月之前的任意月,注意这个add方法会改变年份,若y为12,则是一年前的时间,若为3,则是(相对现在)三个月前的时间
logger.info("计算时间点:" + Util.formatDateTime(cld.getTime()));
/**
public static String formatDateTime(Date date) {
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return outFormat.format(date);
}
*/
long atime = cld.getTimeInMillis();//long型时间atime
cld.add(Calendar.MONTH, -1);//一个月之前
String month = Util.formatDate(cld.getTime(), "yyyy-MM");
logger.info("存档月份:" + month);//若现在是2007-7,则这里是2007-6

List blist = this.getBoardService().findBoardsByParentID(0, 1, -1, Constant.FIND_BOARDS_BY_ORDER);//以前讲过,从最顶层找起!useStat=1,hidden=-1,0
//Criteria c.addOrder(Order.asc("orders"));
for (int i = 0; i < blist.size(); i++) {
Board b = (Board) blist.get(i);
if (b.getBoardType() == 3) {
this.createForumArchivesFile(b, atime, month);
}
List bclist = this.getBoardService().findBoardsByParentID(b.getId(), 1, -1,
Constant.FIND_BOARDS_BY_ORDER);//各大版块的子版!
for (int j = 0; j < bclist.size(); j++) {
Board bc = (Board) bclist.get(j);
if (bc.getBoardType() == 3) {
this.createForumArchivesFile(bc, atime, month);
}//我认为这个方法少了对子版的子版的深度保存!!!
}
}
}
}
@SuppressWarnings("unchecked")
private void createForumArchivesFile(Board b, long atime, String month) throws BbscsException {
if (!BBSCSUtil.ArchivesMonthInFile(b.getId(), month)) { //所在月没存过!
/**

public static List getArchivesMonths(long bid) {
List l = new ArrayList();
File archivesMonthsFile = new File(Constant.ROOTPATH + "archives/archivesmonths-" + bid + ".txt");
String month = "";
try {
month = FileUtils.readFileToString(archivesMonthsFile, Constant.CHARSET);
} catch (IOException e) {
return l;
}
String[] months = month.split(",");
if (months.length > 0) {
for (int i = (months.length - 1); i >= 0; i--) {
if (StringUtils.isNotBlank(months[i])) {
l.add(months[i]);
}
}
}
return l; //archivesMonthsFile-bid.txt中存的是这个bid的存档时间!
}

public static boolean ArchivesMonthInFile(long bid, String month) {
List l = getArchivesMonths(bid);
for (String m : l) { //JDK5.0
if (m.equalsIgnoreCase(month)) {
return true;
}
}
return false;
}
*/
try {
this.getTempConfiguration().setDirectoryForTemplateLoading(
new File(Constant.ROOTPATH + Constant.FTL_PATH));//public static String FTL_PATH = "WEB-INF/templates/";
this.getTempConfiguration().setDefaultEncoding(Constant.CHARSET);
this.getTempConfiguration().setNumberFormat("0.##########");
Locale locale = new Locale("zh", "CN");//前者指语言后者是国家
this.getTempConfiguration().setLocale(locale);
Template temp = this.getTempConfiguration().getTemplate("archivesPostMain.ftl");//产生一个Template!!!
我们用记事本等工具打开它
/**

${month}<#list mainlist as fm>
主题回复作者发帖时间
${fm["title"]}[+${fm["renum"]}]${fm["username"]}${fm["postTime"]}
分页:${pagebreak}
*/ long total = this.getForumHistoryDAO().getForumNumBeforeDate(b.getId(), atime);//历史帖子数(注: 历史帖是3个月以前的帖子,系统每天会把3个月以前的帖子写入历史帖。) if (total > 0) { //有过时(超过3个月的)帖子时,把month写入 BBSCSUtil.writeMonthToFile(b.getId(), month);//month是存储时间而已 } int allPage = (int) Math.ceil((total + 40 - 1) / 40); /** Math.ceil(x):比x大的最小值。 Math.round(x):四舍五入。 Math.floor(x):比x小的最大值。 Math.round(x)返回long型,其余的返回double 型。 */ logger.info(b.getBoardName() + " total:" + total + " allPage:" + allPage); for (int i = 1; i <= allPage; i++) { int spage = (i - 1) * 40;开始记录数编号 List l = this.getForumHistoryDAO().findForumsBeforeDate(b.getId(), atime, spage, 40); /** public List findForumsBeforeDate(final long bid, final long atime, final int firstResult, final int maxResults) { final String sql = "from " + this.getObjName() + " where boardID = ? and isNew = 1 and postTime < ? order by postTime desc"; return getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session s) throws HibernateException, SQLException { Query query = s.createQuery(sql); query.setLong(0, bid); query.setLong(1, atime); query.setFirstResult(firstResult); query.setMaxResults(maxResults); List list = query.list(); return list; } }); } */ List mainlist = new ArrayList(); for (int j = 0; j < l.size(); j++) { Forum f = (Forum) l.get(j); //Forum通用BEAN! Map pmap = new HashMap(); pmap.put("id", f.getMainID()); pmap.put("title", f.getTitle()); pmap.put("renum", f.getReNum()); pmap.put("username", f.getUserName()); pmap.put("postTime", Util.formatDate6(new Date(f.getPostTime()))); /** public static String formatDate6(Date myDate) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String strDate = formatter.format(myDate); return strDate; } */ pmap.put("postdir", Util.formatDate4(new Date(f.getPostTime())) + "/" + (f.getPostTime() % 100) + "/"); /** public static String formatDate4(Date myDate) { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); String strDate = formatter.format(myDate); return strDate; } */ mainlist.add(pmap); //用于历史帖列表显示吧!所以不用内容! List fl = this.getForumHistoryDAO().findForumsTopic(b.getId(), f.getId(), 0, 0, -1, new OrderObj[] { new OrderObj("postTime", Constant.ORDER_ASC) });//以它为主帖,返回按postTime的回复List List topiclist = new ArrayList(); for (int x = 0; x < fl.size(); x++) { Forum tf = (Forum) fl.get(x); Map tmap = new HashMap(); tmap.put("id", tf.getMainID()); tmap.put("title", tf.getTitle()); tmap.put("username", tf.getUserName()); tmap.put("posttime", Util.formatDateTime(new Date(tf.getPostTime()))); tmap.put("content", this.getForumDetail(tf, b).toString()); /** private StringBuffer getForumDetail(Forum f, Board board) { StringBuffer sb = new StringBuffer(); if (StringUtils.isNotBlank(f.getQuoteText())) { sb.append(""); sb.append("引用"); sb.append(": "); if (f.getQuoteEditType() == 0) { sb.append(BBSCSUtil.filterText(f.getQuoteText(), (board.getAllowHTML() == 1), (board.getAllowUBB() == 1), true)); } else { sb.append(BBSCSUtil.filterScript(f.getQuoteText())); } sb.append(""); } if (f.getHaveAttachFile() != 0 && f.getAttachFileName() != null && !f.getAttachFileName().isEmpty()) { sb.append(this.getAttachFile(f)); //有附件!!! } else { sb.append(""); } if (f.getIsVote() == 0) { String detail = this.getForumDetail(f); if (f.getEditType() == 0) { sb.append(BBSCSUtil.filterText(detail, (board.getAllowHTML() == 1), (board.getAllowUBB() == 1), true)); } else { sb.append(BBSCSUtil.filterScript(detail)); } } else { if (f.getEditType() == 0) { sb.append(BBSCSUtil.filterText(f.getDetail(), (board.getAllowHTML() == 1), (board.getAllowUBB() == 1), true)); } else { sb.append(BBSCSUtil.filterScript(f.getDetail())); } } return sb; } 对于getAttachFile()方法我们省略分析之,我们看下: public static String filterText(String sign, boolean useHTML, boolean useUBB, boolean useSmile) { if (!useHTML) { sign = TextUtils.htmlEncode(sign); } if (useUBB) { sign = getUBB2HTML(sign); } if (useSmile) { sign = replaceSmile(sign); } sign = sign.replaceAll(" ", " "); sign = filterScript(sign); return sign; } public static String getFileTypeIcon(String fileExt) { String fileTypeIcon = (String) Constant.ICON_MAP.get(fileExt); if (fileTypeIcon == null) { fileTypeIcon = "default.icon.gif"; } return fileTypeIcon; } 需要注意的是ICON_MAP在Constant中有定义值了! */ topiclist.add(tmap); if (x != 0) { //非第一个帖,就是mainID是自己的帖子! this.forumArchivesDAO.saveForumArchives(b.getId(), tf);//存档! this.getForumHistoryDAO().removeForum(tf);//从历史帖中删除之 } } Template temptopic = this.getTempConfiguration().getTemplate("archivesPostTopic.ftl"); /**下面是这个ftl的部分代码: <#list topiclist as fm> ${fm["title"]} 作者:${fm["username"]} (发表时间:${fm["posttime"]}) ${fm["content"]} */ OutputStream out = new FileOutputStream(BBSCSUtil.getArchivesPostTopicPath(b.getId(), month, f .getPostTime()) + f.getId() + ".html"); /** public static String getArchivesPostMainListWebPath(long bid, String month) { StringBuffer sb = new StringBuffer(); sb.append("archives/"); sb.append(bid); sb.append("/"); sb.append(month); sb.append("/"); return sb.toString(); } public static String getArchivesPostTopicPath(long bid, String month, long posttime) { StringBuffer sb = new StringBuffer(); sb.append(Constant.ROOTPATH); sb.append(getArchivesPostMainListWebPath(bid, month)); sb.append(Util.formatDate4(new Date(posttime))); sb.append("/"); sb.append((posttime % 100)); sb.append("/"); File ft = new File(sb.toString()); if (!ft.exists()) { ft.mkdirs(); } return sb.toString(); } */ Writer writer = new OutputStreamWriter(out, Constant.CHARSET); Map root = new HashMap(); root.put("topoctitle", f.getTitle()); root.put("topiclist", topiclist); temptopic.process(root, writer); writer.flush();//处理f存档! this.forumArchivesDAO.saveForumArchives(b.getId(), f);//保存好f this.getForumHistoryDAO().removeForum(f);//从历史帖中删除之 } StringBuffer sb = new StringBuffer(); for (int x = 1; x <= allPage; x++) { sb.append("["); if (x == i) { sb.append(""); sb.append(x); sb.append(""); } else { sb.append(x); } sb.append("] "); } OutputStream out = new FileOutputStream(BBSCSUtil.getArchivesPostMainListPath(b.getId(), month) + i + ".html"); //i是页码,如果有30页的话,那就是30个文件了! Writer writer = new OutputStreamWriter(out, Constant.CHARSET); Map root = new HashMap(); root.put("boardName", b.getBoardName()); root.put("month", month); root.put("mainlist", mainlist); root.put("pagebreak", sb.toString()); temp.process(root, writer);//这些参数与文件中的参数一致! writer.flush(); } } catch (Exception e) { logger.error(e); throw new BbscsException(e); } } } 对于上面的部分可以查看历史帖选项查看效果!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: