bbscs 二

而另外一个是文件上传操作!贴子附件上传和用户信息写入文件两种:它们都在com.laoer.bbscs.fio中,有三个接口:CommendFileIO,ForumUploadFile,UserInfoFileIO,另外,这个包里也提供了一个javabean:UploadFile,有两个上传文件需要用到的属性fileName和InputStream类型的inputStream,它们提供了对外实用方法..我们一个一个看它们的实现过程,CommendFileIO是推荐内容,我们曾讲过,safe/include/...两个文件,而本forum用到的是另外两个:
ForumUploadFile中有
public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException; //sysConfig用于获得系统的配置参数!,这里也用到了UploadFile这个javabean!
public void delUploadFile(Forum f) throws IOException;
public List delUploadFile(Forum f, List fileNames) throws IOException;
public void moveUploadFile(Forum forum, long tobid) throws IOException;
public void delDetailFile(Forum forum) throws IOException;
我们看它的实现,由于实现它是通过spring注入的!
<bean id="userInfoFileIO"
  class="com.laoer.bbscs.fio.imp.UserInfoFileIOImp">
  <property name="userConfig">
   <ref bean="userConfig" />
  </property>
  <property name="sysConfig">
   <ref bean="sysConfig" />
  </property>
</bean>
<bean id="forumUploadFile"
  class="com.laoer.bbscs.fio.imp.ForumUploadFileImp" />
<bean id="commendFileIO"
  class="com.laoer.bbscs.fio.imp.CommendFileIOImp" />
这个类也先使用了forumConfig及其getter/setter!(不过怎么没注入呢)我们看其:
public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException {
  OutputStream bos = new FileOutputStream(toFileName);
  IOUtils.copy(uploadFile.getInputStream(), bos);
  if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) {
   ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig
     .getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(),1);//缩微图的生成,同目录内!public static String IMG_SMALL_FILEPREFIX = "_Small";
  }
---------->
public boolean isAttachImg(String fileName) {
  return FilenameUtils.isExtension(fileName, getAttachImgTypes());
}
public String[] getAttachImgTypes() {
  String[] types = getAttachImgType().split(","); 
  if (types == null || types.length == 0) { //提供默认值!
   types = new String[3];
   types[0] = "gif";
   types[1] = "jpg";
   types[2] = "jpeg";
  }
  return types;
}
public String getAttachImgType() {
  return this.getStringValue("AttachImgType");
}
public int getReduceAttachImg() {
  return this.getIntValue("ReduceAttachImg", 1);
}
是图片且系统允许生成!
public int getReduceAttachImgSize() {
  return this.getIntValue("ReduceAttachImgSize", 200);
}//长宽都用这个
注意我们将继续深入下去:
FilenameUtils是org.apache.common.io下的!而ImgUtil.reduceImg则是com.laoer.bbscs.comm包里的工具类:(这个类就只有一个方法),我们摘入主要的一段:
public static void reduceImg(String imgsrc, String imgdist, int widthdist, int heightdist, int benchmark) {

  // int benchmark说明:0,长宽哪个长,以哪个为标准;1,以宽为基准;2,以高为基准
  try {
   File srcfile = new File(imgsrc);
   if (!srcfile.exists()) {
    return;
   }
   Image src = javax.imageio.ImageIO.read(srcfile);
   int width = src.getWidth(null);
   int height = src.getHeight(null);

   if (width <= widthdist && height <= heightdist) {
    // SysUtil.cpoyFile(imgsrc, imgdist);
    FileUtils.copyFile(new File(imgsrc), new File(imgdist));
    return;
   }
// 宽度除以高度的比例
   float wh = (float) width / (float) height;
if(benchmark==0) {
...
}
if (benchmark == 1) {
    float tmp_heigth = (float) widthdist / wh;
    BufferedImage tag = new BufferedImage(widthdist, (int) tmp_heigth, BufferedImage.TYPE_INT_RGB);
    tag.getGraphics().drawImage(src, 0, 0, widthdist, (int) tmp_heigth, null);
    FileOutputStream out = new FileOutputStream(imgdist);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(tag);
    out.close();
   }
...主要还是BufferedImage和JPEGCodec.createJPEGEncoder!
对于ForumUploadFileImp中的其它方法我们在用到的时候在来考虑之.
好,我们看看UserInfoFileIO的writeUserInfo(ui),对于这个文件的效果见:safe/user目录下!我们首先注入的是userConfig和sysConfig两个配置服务!下面是某用户文件中的内容:
402881e513bdc8550113bdf70a1b0019|1184303089000|1184303117000|0|0|0|0|100|0|0|0|0|-|本机地址|
用户ID|注册时间|登录时间|文章数|精华文章数|用户头衔|用户生命值(不一定)|积分|......|社区币|是否有相片|(有的话,图片名,无 为"-")|(有的话,用户来自)|
我们看其中的一段代码:
if (StringUtils.isBlank(userInfo.getUserFrom())) {
   sb.append("-");
  } else {
   sb.append(userInfo.getUserFrom());
  }
  sb.append("|");
  File usrfile = new File(this.getUserConfig().getUserFilePath(userInfo.getId()) + Constant.USER_PROFILE);//public static final String USER_PROFILE = "UserProFile.txt";
  FileUtils.writeStringToFile(usrfile, sb.toString(), Constant.CHARSET);
//关于userConfig其实与sysConfig和ForumConfig类似,提供的是简单的配置方法:
注入了safePath:(以前讲过,这里重复一次)
public String getUserFilePath(String userID) {
  StringBuffer sb = new StringBuffer();
  int num = Math.abs(userID.hashCode());
  sb.append(this.getSafePath());
  if (!this.getSafePath().endsWith("/")) {
   sb.append("/");
  }
  sb.append("user/");
  sb.append(num % 100);
  sb.append("/");
  sb.append(userID);
  sb.append("/");
  File ft = new File(sb.toString());
  if (!ft.exists()) {
   ft.mkdirs();
  }
  return sb.toString();
}
好了,看下面的方法:(较长)
public Forum createReForum(Forum forum, Forum mainForum, Board board, UserInfo ui, UploadFile uploadFile,
   boolean isQuote) throws BbscsException {
  try {
   String detail = forum.getDetail();
   if (board.getAuditPost() == 0) { // 不需要审核
    mainForum.setLastPostNickName(forum.getNickName());
    mainForum.setLastPostTitle(forum.getTitle());
    mainForum.setLastPostUserName(forum.getUserName());
    mainForum.setLastTime(forum.getPostTime());
    mainForum.setReNum(mainForum.getReNum() + 1);//加入回复数
    if (forum.getParentID().equals(forum.getMainID())) { // 回复的是主帖
     if (mainForum.getCanNotRe() == 0) {
      mainForum.setCanNotRe(1);//已经回复
     }
     if (isQuote) {
      forum.setQuoteEditType(mainForum.getEditType());//引用编辑类型!
      if (this.getSysConfig().getQuoteMaxSize() > 0) {// public int getQuoteMaxSize() {
  return this.getIntValue("QuoteMaxSize", 300);
}
       forum.setQuoteText(BBSCSUtil.getSpeShortString(this.getForumDetail(mainForum, false), this
         .getSysConfig().getQuoteMaxSize(), "..."));
/**
public String getForumDetail(Forum forum, boolean forcefromfile) {
  if (Constant.POST_STORAGE_MODE == 0) {
   return forum.getDetail();//直接从对象得到!
  } else {
   if (forcefromfile) {
    return this.getForumDetailFromFile(forum);//从文件来
   } else {//从Cache来
    String detail = (String) this.getPostCache().get(forum.getId());
    if (detail == null) {//没有的话,从文件来
     detail = this.getForumDetailFromFile(forum);
     if (StringUtils.isNotBlank(detail)) {
      postCache.add(forum.getId(), detail);
     }
    }
    return detail;
   }
  }
}
注意这里用了一个私有方法:
private String getForumDetailFromFile(Forum forum) {
  File postFile = new File(forumConfig.getForumPath(forum.getBoardID(), forum.getPostTime()) + forum.getDetail());
  try {
   return FileUtils.readFileToString(postFile, Constant.CHARSET);//把文件写成字符串!
  } catch (IOException e) {
   logger.error(e);
   return "";
  }
}
这里用了BBSCSUtil工具类,用于截取一定长度的引用文本内容!
public static String getSpeShortString(String s, int len, String fillstr) {
  int ilen = Math.max(0, len - fillstr.length());300-3=297!0与它比较之
  char ch = ' '
  int reallen = 0;
  for (int i = 0; i < s.length(); i++) {
   ch = s.charAt(i);
   if (((int) ch > 32) && ((int) ch < 128)) { //Ascill
    reallen++;
   } else {
    reallen += 2;
   }
  }
  if (reallen <= len) {
   return s;
  }
  StringBuffer buf = new StringBuffer();
  reallen = 0;
  for (int i = 0; i < s.length(); i++) {
   ch = s.charAt(i);
   buf.append(ch);
   if (((int) ch > 32) && ((int) ch < 128)) {
    reallen++;
   } else {
    reallen += 2;
   }
   if (reallen >= ilen) {
    return buf.append(fillstr).toString();
   }
  }
  return buf.toString();
}
*/
      } else {       
       forum.setQuoteText(this.getForumDetail(mainForum, false));
      }
     }
    }
   } else {  //需要审核帖子!!!!
    mainForum.setLastPostTitle(forum.getTitle());
    mainForum.setLastTime(forum.getPostTime());//不加入回复数
    if (forum.getParentID().equals(forum.getMainID())) { // 回复的是主帖
     if (isQuote) {
      forum.setQuoteEditType(mainForum.getEditType());
      if (this.getSysConfig().getQuoteMaxSize() > 0) {
       forum.setQuoteText(BBSCSUtil.getSpeShortString(this.getForumDetail(mainForum, false), this
         .getSysConfig().getQuoteMaxSize(), "..."));
      } else {
       forum.setQuoteText(this.getForumDetail(mainForum, false));
      }
     }
    }
   }//结束了大的if!注意两者由于主贴有特别的edittype,才对mainForum进行操作!
   mainForum = this.getForumDAO().saveOrUpdateForum(mainForum);//更新
   if (mainForum.getReNum() == this.getSysConfig().getForumHotRes()) { // 回复次数达到热贴标准,增加发帖人人缘系数
    UserInfo mui = this.getUserInfoDAO().findUserInfoById(mainForum.getUserID());
    if (mui != null) {
     mui.setUserKnow(mui.getUserKnow() + 1);
     this.getUserInfoDAO().saveUserInfo(mui);
     this.getUserInfoFileIO().writeUserFile(mui);
    }//更新用户信息
   }
   Forum reForum = mainForum;//假的!
   if (!forum.getParentID().equals(forum.getMainID())) { // 回复的不是主帖
    reForum = this.getForumDAO().findForumByID(forum.getParentID(), forum.getBoardID());
    if (reForum != null) {
     if (reForum.getCanNotRe() == 0) {
      reForum.setCanNotRe(1);
      reForum = this.getForumDAO().saveOrUpdateForum(reForum);//保存真正所回复的帖子信息!
     }
     if (isQuote) {
      forum.setQuoteEditType(reForum.getEditType());
      String reDetail = this.getForumDetail(reForum, false);
      if (this.getSysConfig().getQuoteMaxSize() > 0) {
       forum.setQuoteText(BBSCSUtil.getSpeShortString(reDetail, this.getSysConfig()
         .getQuoteMaxSize(), "..."));
      } else {
       forum.setQuoteText(reDetail);
      }
     }
    }
   }

   // 处理文章标题
   if (forum.getTitle().equalsIgnoreCase(Constant.RE)) {
    if (reForum != null) {
     if (reForum.getTitle().startsWith(Constant.RE)) {
      forum.setTitle(reForum.getTitle());//如果主贴有re:,则回贴一致有!
     } else {
      if (BBSCSUtil.getSysCharsetStrLength(Constant.RE + reForum.getTitle()) > 90)
/**
public static int getSysCharsetStrLength(String txt) {
  try {
   return txt.getBytes(Constant.CHARSET).length;
  } catch (UnsupportedEncodingException ex) {
   return txt.length();
  }
}
*/
{
       forum.setTitle(reForum.getTitle());
      } else {
       forum.setTitle(Constant.RE + reForum.getTitle());
      }
     }
    }
   }

   forum = this.getForumDAO().saveOrUpdateForum(forum);//更新下回贴!
//下面是附件的操作!
   if (Constant.POST_STORAGE_MODE == 0) {
    if (uploadFile != null) {
     String fileName = "File_" + forum.getId() + "_" + System.currentTimeMillis() + "."
       + FilenameUtils.getExtension(uploadFile.getFileName());
     String toFilePath = BBSCSUtil.getUpFilePath(forum.getBoardID(), forum.getPostTime());
     this.getForumUploadFile().saveUploadFile(toFilePath + fileName, uploadFile, this.getSysConfig());
     forum.setHaveAttachFile(1);
     forum.getAttachFileName().add(fileName);
     forum = this.getForumDAO().saveOrUpdateForum(forum);
    }
   } else {
    if (uploadFile != null) {
     String fileName = "File_" + forum.getId() + "_" + System.currentTimeMillis() + "."
       + FilenameUtils.getExtension(uploadFile.getFileName());
     String toFilePath = BBSCSUtil.getUpFilePath(forum.getBoardID(), forum.getPostTime());
     this.getForumUploadFile().saveUploadFile(toFilePath + fileName, uploadFile, this.getSysConfig());
     forum.setHaveAttachFile(1);
     forum.getAttachFileName().add(fileName);

    }

    String postFileName = "P_" + forum.getBoardID() + "_" + forum.getId() + ".txt";
    File postFile = new File(this.getForumConfig().getForumPath(forum.getBoardID(), forum.getPostTime())
      + postFileName);
    FileUtils.writeStringToFile(postFile, detail, Constant.CHARSET);
    forum.setDetail(postFileName);

    forum = this.getForumDAO().saveOrUpdateForum(forum);
   }

   if (board.getAuditPost() == 0 && board.getAddUserPostNum() == 1) { // 不需要审核,并且版区为增加用户发帖数量
    ui.setArticleNum(ui.getArticleNum() + 1);
    ui.setExperience(ui.getExperience() + 1); // 回帖增加经验值1点。
    ui = this.getUserInfoDAO().saveUserInfo(ui);
    this.getUserInfoFileIO().writeUserFile(ui);//写入用户文件!
   }

   if (forum.getEmailInform() != 0 || forum.getMsgInform() != 0) {
    Subscibe subs = this.getSubscibeFactory().getInstance(forum.getBoardID());
    subs.setBoardID(forum.getBoardID());
    subs.setCreateTime(new Date());
    subs.setEmailinform(forum.getEmailInform());
    subs.setMsginform(forum.getMsgInform());
    subs.setNickName(ui.getNickName());
    subs.setPostID(forum.getId());
    subs.setPostTitle(forum.getTitle());
    subs.setUserEmail(ui.getEmail());
    subs.setUserID(ui.getId());
    subs.setUserName(ui.getUserName());
    subs.setUserLocale(ui.getUserLocale());
    this.getSubscibeDAO().saveSubscibe(subs);
   }
   this.getSubscibeQueue().add(forum);
/**加入队列中!是一个同步访问方法:
public synchronized void add(Object o) {
  aVector.add(o);
}
*/
   return forum;
  } catch (Exception ex) {
   logger.error(ex);
   throw new BbscsException(ex);
  }
}

这个时候,让我们回顾一下applicationContext.xml中的内容:
          <bean id="forumServiceTarget"
  class="com.laoer.bbscs.service.imp.ForumServiceImp">
  <property name="forumDAO">
   <ref local="forumMainDAO" />
  </property>
  <property name="userInfoDAO">
   <ref local="userInfoDAO" />
  </property>
  <property name="forumUploadFile">
   <ref local="forumUploadFile" />
  </property>
  <property name="sysListObjCache">
   <ref local="sysListObjCache" />
  </property>
  <property name="sysConfig">
   <ref local="sysConfig" />
  </property>
  <property name="userInfoFileIO">
   <ref local="userInfoFileIO" />
  </property>
  <property name="subscibeFactory">
   <ref local="subscibeFactory" />
  </property>
  <property name="subscibeDAO">
   <ref local="subscibeDAO" />
  </property>
  <property name="boardDAO">
   <ref local="boardDAO" />
  </property>
  <property name="subscibeQueue">
   <ref local="subscibeQueue" />
  </property>
  <property name="forumBuyDAO">
   <ref local="forumBuyDAO" />
  </property>
  <property name="voteDAO">
   <ref local="voteDAO" />
  </property>
  <property name="voteItemDAO">
   <ref local="voteItemDAO" />
  </property>
  <property name="commendDAO">
   <ref local="commendDAO" />
  </property>
  <property name="commendFileIO">
   <ref local="commendFileIO" />
  </property>
  <property name="forumHistoryDAO">
   <ref local="forumHistoryDAO" />
  </property>
  <property name="forumConfig">
   <ref local="forumConfig" />
  </property>
  <property name="postCache">
   <ref local="postCache" />
  </property>
</bean>
OK!Go On!下面是创建投票帖子的,省略了后面的部分!
public Forum createVoteForum(Forum forum, Board board, Vote vote, UserInfo ui, String voteItem)
   throws BbscsException {
  try {
   String[] details = voteItem.split(" ");//投票项字符串数组!

   vote = this.getVoteDAO().saveVote(vote);//Vote保存!
   for (int i = 0; i < details.length; i++) {
    VoteItem vi = new VoteItem();
    vi.setItem(details[i]);
    vi.setItemValue(0);
    vi.setVoteID(vote.getId());
    this.getVoteItemDAO().saveVoteItem(vi);//VoteItem保存
   }
   forum.setVoteID(vote.getId());
   forum = this.getForumDAO().saveOrUpdateForum(forum);

   forum.setMainID(forum.getId());
   forum = this.getForumDAO().saveOrUpdateForum(forum);//帖子保存
....
下面这个是删除真实帖子的文件及从数据库中把数据删除之!
public void delPostReal(Forum forum) throws BbscsException {
  try {
  
   if (Constant.POST_STORAGE_MODE == 1) {
    this.getForumUploadFile().delDetailFile(forum);
   }
   this.getForumUploadFile().delUploadFile(forum);
   this.getForumDAO().removeForum(forum);
  } catch (Exception ex) {
   logger.error(ex);
   throw new BbscsException(ex);
  }
}
其中,由delDetailFile删除帖子内容文件,delUploadFile删除附件文件!
public void delDetailFile(Forum forum) throws IOException {

  File postFile = new File(this.getForumConfig().getForumPath(forum.getBoardID(), forum.getPostTime())
    + forum.getDetail());
  if (postFile.exists()) {
   FileUtils.forceDelete(postFile);
  }
}
public void delUploadFile(Forum f) throws IOException {
  if (f.getHaveAttachFile() == 1 && f.getAttachFileName() != null && f.getAttachFileName().size() > 0) {
   List fl = f.getAttachFileName();
   String filePath = BBSCSUtil.getUpFilePath(f.getBoardID(), f.getPostTime());
   for (int i = 0; i < fl.size(); i++) {
    File attachFile = new File(filePath + (String) fl.get(i));
    if (attachFile.exists()) {
     FileUtils.forceDelete(attachFile);
    }
    File attachFileSmall = new File(filePath + (String) fl.get(i) + Constant.IMG_SMALL_FILEPREFIX);
    if (attachFileSmall.exists()) {
     FileUtils.forceDelete(attachFileSmall);
    }
   }
  }
}

接下来,看下复杂的方法:(delaPost(Forum forum,Board board,UserInfo ui)差不多!
public void delPosts(List forums, Board board) throws BbscsException {
  for (int i = 0; i < forums.size(); i++) {
   try {
    Forum forum = (Forum) forums.get(i);
    if (forum.getAuditing() == 0) { // 如果已近是通过审核的帖子
     forum = this.getForumDAO().saveOrUpdateForum(forum); // 保存标注删除,包括删除人、时间等信息  ????
     if (forum.getIsNew() != 1) { // 如果不是主帖
      Forum mainForum = this.getForumDAO().findForumByID(forum.getMainID(), forum.getBoardID()); // 取主帖
      if (mainForum != null) {
       mainForum.setReNum(mainForum.getReNum() - 1); // 减少主帖回复数
       if (mainForum.getLastTime() == forum.getPostTime()) { // 如果删除的是最后一个回复帖,要修正主帖表中最后回复人和时间
        OrderObj[] oo = { new OrderObj("postTime", Constant.ORDER_DESC) };//查询条件吧!OrderObj是com.laoer.bbscs.comm里面的一个javaBean类,它有两个属性orderBy和ascOrDesc=Constant.ORDER_DESC;
/**
public OrderObj(String orderBy, int ascOrDesc) {
    this.orderBy = orderBy;
    this.ascOrDesc = ascOrDesc;
  }
*/
        List l = this.getForumDAO().findForumsTopic(mainForum.getBoardID(), mainForum.getId(),
          0, 0, oo, 0, 1);//参见DAO!!!
        if (l != null && !l.isEmpty()) {
         Forum lastF = (Forum) l.get(0);
         mainForum.setLastPostNickName(lastF.getNickName());
        mainForum.setLastPostTitle(lastF.getTitle());
         mainForum.setLastPostUserName(lastF.getUserName());
         mainForum.setLastTime(lastF.getPostTime());
        }
       }
       this.getForumDAO().saveOrUpdateForum(mainForum); // 保存主帖
      }
     }
     UserInfo ui = this.getUserInfoDAO().findUserInfoById(forum.getUserID());
     if (board.getAddUserPostNum() == 1 && ui != null) { // 版区为增加用户发帖数量
      if (ui.getArticleNum() > 0) {
       ui.setArticleNum(ui.getArticleNum() - 1); // 减少用户发帖数
       ui = this.getUserInfoDAO().saveUserInfo(ui);
       this.getUserInfoFileIO().writeUserFile(ui);
      }

      if (forum.getIsNew() == 1) {
       ui.setExperience(ui.getExperience() - 2); // 主帖,扣除发帖人2点经验值
      } else {
       ui.setExperience(ui.getExperience() - 1); // 回帖,扣除发帖人1点经验值
      }
     }
     if (forum.getElite() != 0 || forum.getCommend() != 0) { // 如果是精华或推荐
      if (forum.getElite() != 0) {
       if (ui.getArticleEliteNum() >= 1) {
        ui.setArticleEliteNum(ui.getArticleEliteNum() - 1);
       } else {
        ui.setArticleEliteNum(0);
       }
       ui.setLiterary(ui.getLiterary() - 3);
      }
      if (forum.getCommend() != 0) {
       ui.setLiterary(ui.getLiterary() - 1);
       this.getCommendDAO().removeCommend(forum.getId());
      }

      ui = this.getUserInfoDAO().saveUserInfo(ui);
      this.getUserInfoFileIO().writeUserFile(ui);
     }

     if (forum.getIsNew() == 1) { // 如果是主帖,尝试从新帖Cache中清除,只有主贴才从Cache去之
      this.getSysListObjCache().remove(Constant.FORUM_NEW_CACHE_NAME);
     }
    } else { // 如果是尚未审核
     forum = this.getForumDAO().saveOrUpdateForum(forum); // 保存标注删除,包括删除人、时间等信息
    }
   } catch (Exception ex) {
    logger.error(ex);
    throw new BbscsException(ex);
   }
  }
}

另外:
public void delPostsReal(List ids) throws BbscsException {
  List forums = this.getForumDAO().findForumsInIds(ids);
  for (int i = 0; i < forums.size(); i++) {
   Forum forum = (Forum) forums.get(i);
   if ((System.currentTimeMillis() - forum.getDelTime()) > 7 * 24 * 3600 * 1000) {//大于7天就真正删除哦!
    try {
     if (Constant.POST_STORAGE_MODE == 1) {
      this.getForumUploadFile().delDetailFile(forum);
     }
     this.getForumUploadFile().delUploadFile(forum);
     this.getForumDAO().removeForum(forum);
    } catch (Exception ex) {
     logger.error(ex);
     throw new BbscsException(ex);
    }
   }
  }
}
看个查找生成分页列表的两个方法:
public PageList findForums(long bid, int isNew, int delSign, int auditing, int auditingAttachFile, OrderObj[] oo,
   Pages pages) {
  PageList pl = new PageList();
  if (pages.getTotalNum() == -1) {
   pages.setTotalNum(this.getForumDAO().getForumNum(bid, isNew, delSign, auditing, auditingAttachFile));
  }
  pages.executeCount();

  List l = this.getForumDAO().findForums(bid, isNew, delSign, auditing, auditingAttachFile, oo, pages.getSpage(),
    pages.getPerPageNum());
  pl.setObjectList(l);
  pl.setPages(pages);
  return pl;
}

public PageList findForumsAll(long bid, Pages pages) {
  OrderObj oo0 = new OrderObj("isTop", Constant.ORDER_DESC);
  OrderObj oo1 = new OrderObj("lastTime", Constant.ORDER_DESC);
  OrderObj[] oo = { oo0, oo1 };
  return this.findForums(bid, -1, 0, 0, -1, oo, pages);
}
还有重载的方法:
public List findForumsAllNew(int num) {
  OrderObj[] oo = { new OrderObj("postTime", Constant.ORDER_DESC) };
  return this.getForumDAO().findForums(-1, 1, 0, 0, -1, oo, 0, num);
}

public List findForumsAllNewCache(int num) {
  List l = (List) this.getSysListObjCache().get(Constant.FORUM_NEW_CACHE_NAME);
  if (l == null) {
   OrderObj[] oo = { new OrderObj("postTime", Constant.ORDER_DESC) };
   l = this.getForumDAO().findForums(-1, 1, 0, 0, -1, oo, 0, num);
   this.getSysListObjCache().add(Constant.FORUM_NEW_CACHE_NAME, l);
  }
  return l;
}

下面是恢复帖子方法:
public void saveForumsResume(List ids, Board board) throws BbscsException {
  List forums = this.getForumDAO().findForumsInIds(ids);
  for (int i = 0; i < forums.size(); i++) {
   Forum forum = (Forum) forums.get(i);
   if (forum.getAuditing() == 0) { // 已通过审核的帖子恢复
    forum.setDelSign(0);
    if (forum.getIndexStatus() == Constant.INDEX_STATUS_NO_INDEX_TO_DEL) {
     forum.setIndexStatus(Constant.INDEX_STATUS_NO_INDEX);
    } else if (forum.getIndexStatus() == Constant.INDEX_STATUS_DELED) {
     forum.setIndexStatus(Constant.INDEX_STATUS_NO_INDEX);
    }
    try {
     this.getForumDAO().saveOrUpdateForum(forum);
     if (!forum.getId().equals(forum.getMainID())) {
      Forum mainForum = this.getForumDAO().findForumByID(forum.getMainID(), forum.getBoardID());
      if (mainForum != null) {  //mainForum修改
       mainForum.setReNum(mainForum.getReNum() + 1);
       this.getForumDAO().saveOrUpdateForum(mainForum);
      }
     }
     if (board.getAddUserPostNum() == 1) {
      UserInfo ui = this.getUserInfoDAO().findUserInfoById(forum.getUserID());
      if (ui != null) {//用户信息修改
       ui.setArticleNum(ui.getArticleNum() + 1);

       if (forum.getIsNew() == 1) {
        ui.setExperience(ui.getExperience() + 2); // 主帖增加2点经验值
       } else {
        ui.setExperience(ui.getExperience() + 1); // 回帖增加1点经验值
       }

       ui = this.getUserInfoDAO().saveUserInfo(ui);
       this.getUserInfoFileIO().writeUserFile(ui);
      }
     }
    } catch (Exception ex) {
     logger.error(ex);
     throw new BbscsException(ex);
    }
   } else { // 未通过审核的被删除的帖子恢复
    forum.setDelSign(0);
    try {
     this.getForumDAO().saveOrUpdateForum(forum);
    } catch (Exception ex1) {
     logger.error(ex1);
     throw new BbscsException(ex1);
    }
   }
  }
}
public static final int INDEX_STATUS_NO_INDEX = 0;
public static final int INDEX_STATUS_INDEXED = 1;
public static final int INDEX_STATUS_NEED_UPDTAE = 2;
public static final int INDEX_STATUS_NEED_DEL = 3;
public static final int INDEX_STATUS_DELED = 4;
public static final int INDEX_STATUS_NO_INDEX_TO_DEL = 5;
        public static final int INDEX_STATUS_UPDATE_TO_DEL = 6;
对于其它类似,不在继续下去了!我们将直接看DAO的实现层:(由于DAO层简单,下面只是列出我个人认为较有代表性的方法)
public List findForums(final long bid, final int isNew, final int delSign, final int auditing, final OrderObj[] oo) {//参数为-1,表示此项忽略,否则为增加相应的条件
  return getHibernateTemplate().executeFind(new HibernateCallback() {
   public Object doInHibernate(Session s) throws HibernateException {
    Criteria c = s.createCriteria(getForumClass());
    if (bid != -1) {
     c.add(Restrictions.eq("boardID", new Long(bid)));
    }
    if (isNew != -1) {
     c.add(Restrictions.eq("isNew", new Integer(isNew)));
    }
    if (delSign != -1) {
     c.add(Restrictions.eq("delSign", new Integer(delSign)));
    }
    if (auditing != -1) {
     c.add(Restrictions.eq("auditing", new Integer(auditing)));
    }
    if (oo != null && oo.length > 0) {
     for (int i = 0; i < oo.length; i++) {
      if (StringUtils.isNotBlank(oo[i].getOrderBy())) {
       if (oo[i].getAscOrDesc() == Constant.ORDER_ASC) {
        c.addOrder(Order.asc(oo[i].getOrderBy()));//Order序!!!
       }
       if (oo[i].getAscOrDesc() == Constant.ORDER_DESC) {
        c.addOrder(Order.desc(oo[i].getOrderBy()));
       }
      }
     }
    }
    return c.list();
   }
  });
}

public List findForumsElite(long bid, long elite, long eliteId) {
  Object[] o = { new Long(bid), new Long(elite), new Long(eliteId), new Integer(0) };
  String sql = "from " + this.getObjName() + " where boardID = ? and elite = ? and eliteID = ? and delSign = ?";
  return this.getHibernateTemplate().find(sql, o);
}
/**
private String getObjName() {
  return "Forum" + this.flag;
}
private String flag = "Main";
*/


public List findForumsRealDelAll(long bid, long atime) {
  Object[] o = { new Long(bid), new Long(atime) };
  String sql = "from " + this.getObjName() + " where boardID = ? and delSign = 1 and delTime < ?";
  return this.getHibernateTemplate().find(sql, o);
}

public List findForumsToHistory(long atime) {
  String sql = "from ForumMain where isNew = 1 and elite = 0 and lastTime <= ?";
  return this.getHibernateTemplate().find(sql, new Long(atime));
}

public long getForumNumHotTopic(long bid, int reNum, int click) {
  Object[] o = { new Long(bid), new Integer(1), new Integer(0), new Integer(0), new Integer(reNum),
    new Integer(click) };
  String sql = "select count(id) from " + this.getObjName()
    + " where boardID = ? and isNew = ? and delSign = ? and auditing = ? and (reNum >= ? or click >= ?)";
  List l = this.getHibernateTemplate().find(sql, o);
  if (l == null || l.isEmpty()) {
   return 0;
  } else {
   return ((Long) l.get(0)).longValue();
  }
}
下面是一个关于搜索帖子的方法:
public List getSearchList(final long bid, final String con, final String text, final int delSign,
   final int auditing, final String orderby, final int ascOrDesc, final int firstResult, final int maxResults) {
  return getHibernateTemplate().executeFind(new HibernateCallback() {
   public Object doInHibernate(Session s) throws HibernateException {
    Criteria c = s.createCriteria(getForumClass());
    c.add(Restrictions.eq("boardID", new Long(bid)));
    c.add(Restrictions.like(con, "%" + text + "%"));
    if (delSign != -1) {
     c.add(Restrictions.eq("delSign", new Integer(delSign)));
    }
    if (auditing != -1) {
     c.add(Restrictions.eq("auditing", new Integer(auditing)));
    }
    if (StringUtils.isNotBlank(orderby)) {
     if (ascOrDesc == Constant.ORDER_ASC) {
      c.addOrder(Order.asc(orderby));
     }
     if (ascOrDesc == Constant.ORDER_DESC) {
      c.addOrder(Order.desc(orderby));
     }
    }
    c.setFirstResult(firstResult);
    c.setMaxResults(maxResults);
    return c.list();
   }
  });
}
其它的省略之!已经将主要的Forum服务给分析完了.OK!




Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1828820


你可能感兴趣的:(sql,C++,c,UI,OO)