com.huang.rp.blog.access.service.AccessService.java Source code

Java tutorial

Introduction

Here is the source code for com.huang.rp.blog.access.service.AccessService.java

Source

/**
 * Copyright (c) 2005-2012 https://github.com/javahuang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.huang.rp.blog.access.service;

import java.io.IOException;
import java.io.StringReader;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.huang.rp.blog.post.dao.BlogAccessLogMapper;
import com.huang.rp.blog.post.domain.*;
import com.huang.rp.blog.tools.dao.BlogToolsMapper;
import com.huang.rp.blog.tools.domain.BlogTools;
import com.huang.rp.blog.tools.domain.BlogToolsExample;
import com.huang.rp.blog.tools.domain.BlogToolsVO;
import com.huang.rp.common.utils.IpUtils;
import com.huang.rp.common.utils.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.huang.rp.blog.access.domain.CookieVO;
import com.huang.rp.blog.access.filter.AccessFilter;
import com.huang.rp.blog.post.dao.BlogPostsMapper;
import com.huang.rp.common.Constants;
import com.huang.rp.common.cache.dao.SysParameterMapper;
import com.huang.rp.common.cache.domain.SysParameter;
import com.huang.rp.common.cache.domain.SysParameterExample;
import com.huang.rp.common.cache.domain.SysParameterExample.Criteria;
import com.huang.rp.common.exception.ServiceException;
import com.huang.rp.common.utils.Encodes;
import com.huang.rp.common.utils.HttpUtils;
import com.huang.rp.sys.rbac.dao.SysUserMapper;
import com.huang.rp.sys.rbac.domain.SysUser;
import com.huang.rp.sys.rbac.domain.SysUserExample;

/**
 * 
 * <p/>
 * <p>User: Huang rp
 * <p>Date: 2015425 ?7:31:07
 * <p>Version: 1.0
 */
@Service
public class AccessService {

    @Autowired
    BlogPostsMapper postMapper;
    @Autowired
    SysParameterMapper sysParameterMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    BlogToolsMapper toolsMapper;
    @Autowired
    BlogAccessLogMapper blogAccessLogMapper;

    /**
     * ?
     * @param post
     */
    public BlogPostsWithBLOBs getArticle(HttpServletRequest request, BlogPostsWithBLOBs post) {
        CookieVO cookieVO = parseCookie(request);
        if (StringUtils.isNotBlank(post.getPostName())) {
            BlogPostsExample exp = new BlogPostsExample();
            exp.createCriteria().andPostNameEqualTo(post.getPostName());
            List<BlogPostsWithBLOBs> postList = postMapper.selectByExampleWithBLOBs(exp);
            if (postList.size() == 1) {
                post = postList.get(0);
            } else {
                throw new ServiceException("500");
            }
        }
        long id = 0;
        if ((id = post.getId()) != 0) {
            post = postMapper.selectByPrimaryKey(id);
        }
        if (post.getPostAuthor() == null)
            throw new ServiceException("500");
        //???
        if (request.getRequestURL().toString().toLowerCase().contains(Constants.WEB_RCL_URL)) {
            return post;
        }
        if (StringUtils.isBlank(post.getPostPassword()))
            return post;
        //??  cookie post?post??  useridid?
        if (StringUtils.isNotBlank(post.getPostPassword())
                && (post.getPostPassword().equals(cookieVO.getPostPassword()) || //??
                        (post.getPostAuthor().equals(cookieVO.getUserId())
                                && StringUtils.isNotBlank(cookieVO.getUserPassword()))))//?
        {// ?
            return post;
        }
        throw new ServiceException("500");
    }

    /**
     * ??
     * @param filter
     * @return
     */
    public List<BlogPostsWithBLOBs> getArticleExcerptListByFilter(HttpServletRequest request, AccessFilter filter) {
        if (filter == null) {
            filter = new AccessFilter();
            filter.setSidx("id");//
            filter.setSord("desc");
        }
        CookieVO cookieVO = parseCookie(request);
        filter.setSearchStr(cookieVO.getSearch());
        filter.setTagId(cookieVO.getTag());
        filter.setUserId(cookieVO.getUserId());
        List<String> searchs = doSearchBefore(filter);
        if (request.getRequestURL().toString().toLowerCase().contains(Constants.WEB_RCL_URL)) {
            filter.setUserId(Constants.WEB_RCL_USER_ID);
        }
        if (filter.getRows() == null)
            filter.setRows(Constants.POST_LIST_PAGE_SIZE);
        List<BlogPostsWithBLOBs> excerptList = postMapper.selectArticleExcerptByFilter(filter);
        List<BlogPostsWithBLOBs> newExcerptList = Lists.newArrayList(excerptList);
        // ??
        for (BlogPostsWithBLOBs post : excerptList) {
            if (StringUtils.isNotBlank(post.getPostPassword()) && StringUtils.isBlank(cookieVO.getUserPassword())) {
                newExcerptList.remove(post);
            }
        }
        excerptList = newExcerptList;
        if (StringUtils.isNotBlank(filter.getSearchStr()) && filter.isHighLight()) {
            ///??
            doSearchAfter(excerptList, searchs);
        }
        return excerptList;
    }

    /**
     * ??
     * ?,????%?
     * ?lucene???
     * @param filter
     * @throws IOException 
     */
    public List<String> doSearchBefore(AccessFilter filter) {
        List<String> searchs = Lists.newArrayList();
        if (StringUtils.isBlank(filter.getSearchStr()))
            return null;
        StringReader sr = new StringReader(filter.getSearchStr());
        IKSegmenter ik = new IKSegmenter(sr, true);
        Lexeme lex = null;
        StringBuilder searchStr = new StringBuilder();
        searchStr.append("%");
        try {
            while ((lex = ik.next()) != null) {
                String lexemeText = lex.getLexemeText();
                searchStr.append(lexemeText + "%");
                searchs.add(lexemeText);
            }
            filter.setSearchStr(searchStr.toString());
            return searchs;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * ?
     * ????
     * ?X?N
     * ??
     * ?X+N
     * //<span style="background-color: rgb(255, 255, 0);"></span>
     * @param excerptList
     */
    public void doSearchAfter(List<BlogPostsWithBLOBs> excerptList, List<String> searchs) {
        if (excerptList.size() == 0)
            return;
        for (BlogPostsWithBLOBs post : excerptList) {
            String postFilter = post.getPostContentFiltered().replace(" ", "");//
            StringBuilder postExcerpt = new StringBuilder();
            //???????
            List<Integer> indexs = Lists.newArrayList();//?
            for (String s : searchs) {
                int n = StringUtils.countMatches(postFilter, s);//? ?
                if (n > 0) {//??
                    int currIndex = 0;
                    for (int i = 0; i < n; i++) {
                        if (i > 5)
                            break;
                        currIndex = postFilter.indexOf(s, currIndex);
                        indexs.add(currIndex);
                        currIndex++;
                    }
                }
            }
            Collections.sort(indexs);//,?20,?
            int tempSub = 0;//
            int size = indexs.size();
            for (int m = 0; m < size; m++) {
                int currentIndex = indexs.get(m);
                if (size - 1 == m) {//?,14
                    postExcerpt.append(getSubStrByMidIndex(postFilter, currentIndex, tempSub));
                    break;
                }
                int nextIndex = indexs.get(m + 1);
                if (nextIndex - currentIndex > 14 && tempSub == 0) {//14,?
                    postExcerpt.append(getSubStrByMidIndex(postFilter, currentIndex, 0) + "&nbsp;");
                } else if (nextIndex - currentIndex > 14 && tempSub != 0) {
                    postExcerpt.append(getSubStrByMidIndex(postFilter, currentIndex, 10 + tempSub) + "&nbsp;");
                } else {
                    tempSub = tempSub + nextIndex - currentIndex;
                }
            }
            String result = postExcerpt.toString();
            for (String s : searchs) {
                result = result.replace(s, "<span style=\"background-color: rgb(255, 255, 0);\">" + s + "</span>");
            }
            post.setPostExcerpt(result);
        }
    }

    /**
     * ???
     * @param srcStr
     * @param index
     * @param sub
     * @return
     */
    public static String getSubStrByMidIndex(String srcStr, int index, int sub) {
        if (sub == 0) {
            sub = 10;//?srcStrindex??
        }
        int begin = index - sub;//??????
        int end = index + 7;//end+7
        if (begin < 0) {
            begin = 0;
        }
        if (end >= srcStr.length()) {
            end = srcStr.length();
        }
        return StringUtils.substring(srcStr, begin, end);
    }

    @Value("${duoshuo.signature}")
    String secret;
    @Value("${duoshuo.url}")
    String duoshuourl;
    @Value("${duoshuo.synccomment}")
    boolean duoshuoSync;

    /**
     * ?
     * @param request
     */
    public void doComment(HttpServletRequest request) {
        //      String action=request.getParameter("action");
        //      String signature=request.getParameter("signature");
        //      String short_name="";
        Map<String, String> params = Maps.newHashMap();
        params.put("secret", secret);
        params.put("short_name", "hrps");
        if (!duoshuoSync)
            return;
        String response = HttpUtils.URLGet(duoshuourl, params, "utf-8");
        System.out.println(response);
    }

    /**
     * ?
     * @return
     */
    public Map<String, Map<String, List<BlogPostsWithBLOBs>>> getTimelineList(HttpServletRequest request,
            AccessFilter filter) {
        if (filter == null)
            filter = new AccessFilter();
        filter.setRows(Integer.MAX_VALUE - 1);
        filter.setSord("desc");
        filter.setSidx("id");
        CookieVO cookieVO = parseCookie(request);
        filter.setSearchStr(cookieVO.getSearch());
        filter.setTagId(cookieVO.getTag());
        filter.setUserId(cookieVO.getUserId());
        filter.setHighLight(true);
        List<BlogPostsWithBLOBs> excerptList = getArticleExcerptListByFilter(request, filter);
        Map<String, Map<String, List<BlogPostsWithBLOBs>>> timeline = Maps.newLinkedHashMap();
        for (BlogPostsWithBLOBs spost : excerptList) {
            Date postDate = spost.getPostDate();
            DateTime dt = new DateTime(postDate.getTime());
            String yearMonthKey = dt.monthOfYear().getAsText(Locale.ENGLISH) + "," + dt.getYearOfEra();////key May,2015?
            Map<String, List<BlogPostsWithBLOBs>> yearMonthPostMap = timeline.get(yearMonthKey);
            if (yearMonthPostMap == null) {
                yearMonthPostMap = Maps.newLinkedHashMap();
                timeline.put(yearMonthKey, yearMonthPostMap);
            }
            String dayKey = "Day" + dt.getDayOfMonth();
            List<BlogPostsWithBLOBs> dayPostList = yearMonthPostMap.get(dayKey);
            if (dayPostList == null) {
                dayPostList = Lists.newArrayList();
                yearMonthPostMap.put(dayKey, dayPostList);
            }
            dayPostList.add(spost);

        }
        return timeline;
    }

    //@Test
    public void test() {
        String s = "abcadefaghj";
        int n = StringUtils.countMatches(s, "a");//? ?
        System.out.println(n);
        if (n > 0) {//??
            int currIndex = 0;
            for (int i = 0; i < n; i++) {
                currIndex = s.indexOf("a", currIndex++);//++? ~
                currIndex++;
                System.out.println(currIndex);
            }
        }
        int index = 6;
        int sub = 3;
        if (index - sub > 0)
            System.out.println(StringUtils.substring(s, index - sub, index + sub));
    }

    /**
     * ? $user username ???
     * @param request
     * @return
     */
    public List<SysParameter> getTagCloud(HttpServletRequest request) {
        SysParameterExample sysParameter = new SysParameterExample();
        Criteria sysParaCa = sysParameter.createCriteria();
        //?user cookie ?? ?para_groupid,?
        CookieVO cookieVO = parseCookie(request);
        if (cookieVO.getUserId() != null) {
            sysParaCa.andParaGroupEqualTo(cookieVO.getUserId().intValue());
        }
        //rencl.me???
        if (request.getRequestURL().toString().toLowerCase().contains(Constants.WEB_RCL_URL)) {
            sysParaCa.andParaGroupEqualTo(Constants.WEB_RCL_USER_ID.intValue());
        }
        List<SysParameter> tagList = sysParameterMapper.selectByExample(sysParameter);
        return tagList;
    }

    //   /**
    //    * $user username ?
    //    * $user username -p password ?
    //    * $password ?
    //    * cookie??
    //    * @param request
    //    * @return
    //    */
    //   public SysUser getUserInfoByCookie(HttpServletRequest request){
    //      String userCookie=getCookieValue(request,Constants.COOKIE_NAME_USER);//user cookie
    //      if(StringUtils.isNotBlank(userCookie)){
    //         if(userCookie.startsWith("$user")){
    //            String password="";
    //            //?? -p
    //            if(StringUtils.containsIgnoreCase(userCookie, "-p")){
    //               password=StringUtils.substringAfterLast(userCookie, "-p");
    //            }
    //            userCookie=userCookie.replace("$user", "").trim();
    //            if(StringUtils.isNotBlank(userCookie)){
    //               SysUserExample userExample=new SysUserExample();
    //               userExample.createCriteria().andUsernameEqualTo(userCookie);
    //               List<SysUser> users=sysUserMapper.selectByExample(userExample);
    //               if(users.size()==1){
    //                  //???,?
    //                  SysUser user=users.get(0);
    //                  if(user.getPassword().equalsIgnoreCase(password)){
    //                     return user;
    //                  }else{
    //                     user.setPassword(null);
    //                     return user;
    //                  }
    //               }
    //            }
    //               
    //         }
    //      }
    //      return null;
    //   }
    //   /**
    //    * ?cookie?
    //    * @param request
    //    * @param cookieName
    //    * @return
    //    */
    //   private String getCookieValue(HttpServletRequest request,String cookieName){
    //      Cookie[]cookies=request.getCookies();
    //      if(cookies!=null){
    //         for(Cookie cookie:cookies){
    //            if(cookieName.equals(cookie.getName())){
    //               String value=Encodes.urlDecode(cookie.getValue());// $user username?
    //               return value;
    //            }
    //         }
    //      }
    //      return null;
    //   }
    /**
     * cookie??CookieVO
     * @param request
     * @return
     */
    public CookieVO parseCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        CookieVO cookieVO = new CookieVO();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //cookie
                String cName = cookie.getName();
                String cValue = Encodes.urlDecode(cookie.getValue());
                if (cName.equalsIgnoreCase(Constants.COOKIE_NAME_TAG)) {
                    cookieVO.setTag(cValue);
                }
                if (cName.equalsIgnoreCase(Constants.COOKIE_NAME_USER)) {
                    String userName = null;
                    String userPassword = null;
                    if (StringUtils.containsIgnoreCase(cValue, "-p")) {
                        userPassword = StringUtils.substringAfterLast(cValue.toLowerCase(), "-p").trim();
                        userName = StringUtils.substringBefore(cValue.toLowerCase(), "-p").replace("$user", "")
                                .trim();
                    } else {
                        userName = cValue.toLowerCase().replace("$user", "").trim();
                    }
                    SysUserExample userExample = new SysUserExample();
                    userExample.createCriteria().andUsernameEqualTo(userName);
                    List<SysUser> users = sysUserMapper.selectByExample(userExample);
                    if (users.size() == 1) {
                        //???,?
                        SysUser user = users.get(0);
                        if (user.getPassword().equalsIgnoreCase(userPassword)) {
                            cookieVO.setUserName(userName);
                            cookieVO.setUserPassword(userPassword);
                        } else {
                            cookieVO.setUserName(userName);
                        }
                        cookieVO.setUserId(user.getId());//idpostAuthor
                    }
                }
                if (cName.equalsIgnoreCase(Constants.COOKIE_NAME_PASSWORD)) {
                    cookieVO.setPostPassword(cValue.toLowerCase().replace("$password", "").trim());
                }
                if (cName.equalsIgnoreCase(Constants.COOKIE_NAME_SEARCH)) {
                    cookieVO.setSearch(cValue);
                }
            }
        }
        return cookieVO;
    }

    /**
     * ?
     * @param request
     * @param filter
     * @return
     */
    public List<BlogPostsWithBLOBs> getArticleList(HttpServletRequest request, AccessFilter filter) {
        if (filter == null)
            filter = new AccessFilter();
        filter.setSord("desc");
        filter.setSidx("id");
        CookieVO cookieVO = parseCookie(request);
        filter.setSearchStr(cookieVO.getSearch());
        filter.setTagId(cookieVO.getTag());
        filter.setUserId(cookieVO.getUserId());
        filter.setHighLight(true);
        List<BlogPostsWithBLOBs> articleList = getArticleExcerptListByFilter(request, filter);
        return articleList;
    }

    /**
     * ??
     * @return
      */
    public List<BlogToolsVO> getBlogTools() {
        BlogToolsExample exp = new BlogToolsExample();
        exp.createCriteria().andIsValidEqualTo(true);
        exp.setOrderByClause("type,sequence");
        List<BlogToolsVO> tools = toolsMapper.selectByExample(exp);
        List<BlogToolsVO> level0Tools = Lists.newArrayList();
        List<BlogToolsVO> level1Tools = Lists.newArrayList();
        List<BlogToolsVO> level2Tools = Lists.newArrayList();
        List<BlogToolsVO> level3Tools = Lists.newArrayList();
        for (BlogToolsVO tool : tools) {
            if (tool.getType() == 0) {
                level0Tools.add(tool);
            } else if (tool.getType() == 1) {
                level1Tools.add(tool);
            } else if (tool.getType() == 2) {
                level2Tools.add(tool);
            } else if (tool.getType() == 3) {
                level3Tools.add(tool);
            }
        }
        addSubTools(level2Tools, level3Tools);
        addSubTools(level1Tools, level2Tools);
        addSubTools(level0Tools, level1Tools);
        return level0Tools;
    }

    private void addSubTools(List<BlogToolsVO> parentTools, List<BlogToolsVO> subTools) {
        for (BlogToolsVO tool : subTools) {//??0
            for (BlogToolsVO tool0 : parentTools) {
                if (tool.getParentId() == tool0.getId()) {
                    List<BlogToolsVO> tool0s = tool0.getSubTools();
                    if (tool0s == null) {
                        tool0s = Lists.newArrayList();
                        tool0.setSubTools(tool0s);
                    }
                    tool0.getSubTools().add(tool);
                }
            }
        }

    }

    /**
     * ???,
     * @param request
      */
    public synchronized void updateBlogPostReadCount(HttpServletRequest request) {
        String url = request.getRequestURI();///blog/article/daily-writing-151222
        String articleName = StringUtils.substringAfterLast(url, "/");
        //??
        if (StringUtils.isBlank(url) || !StringUtils.contains(url, "article")) {
            return;
        }
        //?
        String agent = request.getHeader("User-Agent");
        if (StringUtils.isNotBlank(agent) && agent.contains("bot")) {
            return;
        }
        String ip = IpUtils.getIpAddr(request);
        BlogAccessLogExample exp = new BlogAccessLogExample();
        exp.createCriteria().andUrlEqualTo(articleName).andIpEqualTo(ip);
        List<BlogAccessLog> blogAccessLogs = blogAccessLogMapper.selectByExample(exp);
        if (blogAccessLogs.size() == 0) {//ip,
            BlogPostsExample postExp = new BlogPostsExample();
            postExp.createCriteria().andPostNameEqualTo(articleName);
            List<BlogPosts> blogPostsList = postMapper.selectByExample(postExp);
            if (blogPostsList.size() == 1) {
                BlogPosts currPost = blogPostsList.get(0);
                BlogPostsWithBLOBs currPostWithBlob = new BlogPostsWithBLOBs();
                currPostWithBlob.setId(currPost.getId());
                currPostWithBlob.setReadCount(currPost.getReadCount() + 1);
                postMapper.updateByPrimaryKeySelective(currPostWithBlob);
            }
        }
        BlogAccessLog blogAccessLog = new BlogAccessLog();
        blogAccessLog.setCreateTime(new Date());
        blogAccessLog.setIp(ip);
        blogAccessLog.setUrl(articleName);
        blogAccessLog.setReferer(request.getHeader("Referer"));
        blogAccessLog.setUserAgent(agent);
        blogAccessLogMapper.insertSelective(blogAccessLog);
    }

}