com.frameworkset.platform.sanylog.action.CounterController.java Source code

Java tutorial

Introduction

Here is the source code for com.frameworkset.platform.sanylog.action.CounterController.java

Source

/*
 * @(#)DocumentController.java
 * 
 * Copyright @ 2001-2012 SANY Group Co.,Ltd.
 * All right reserved.
 * 
 * bbossgroups?????
 * ?bbossgroups?????
 * This software is the confidential and proprietary information
 * of SANY Group Co, Ltd. You shall not disclose such
 * Confidential Information and shall use it only in accordance
 * with the terms of the license agreement you entered into with
 * SANY Group Co, Ltd.
 */
package com.frameworkset.platform.sanylog.action;

import java.net.URLDecoder;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tools.ant.util.DateUtils;
import org.frameworkset.util.CollectionUtils;
import org.frameworkset.util.annotations.PagerParam;
import org.frameworkset.util.annotations.ResponseBody;
import org.frameworkset.web.servlet.ModelMap;

import com.frameworkset.orm.transaction.TransactionManager;
import com.frameworkset.platform.sanylog.bean.App;
import com.frameworkset.platform.sanylog.bean.BrowserCounter;
import com.frameworkset.platform.sanylog.bean.BrowserVisitInfo;
import com.frameworkset.platform.sanylog.bean.Module;
import com.frameworkset.platform.sanylog.bean.OperChart;
import com.frameworkset.platform.sanylog.bean.OperRank;
import com.frameworkset.platform.sanylog.bean.OperateCounter;
import com.frameworkset.platform.sanylog.bean.VideoHitsCounter;
import com.frameworkset.platform.sanylog.dictionary.Dictionary;
import com.frameworkset.platform.sanylog.service.ConfigManager;
import com.frameworkset.platform.sanylog.service.CounterManager;
import com.frameworkset.platform.sanylog.util.POIExcelUtil2007;
import com.frameworkset.platform.security.AccessControl;
import com.frameworkset.util.ListInfo;
import com.frameworkset.util.StringUtil;

/**
 * @author gw_hel
 * ?
 */
public class CounterController {

    private final String[] browserTypeSet = { "MSIE", "Firefox", "Safari", "Chrome" };
    private ConfigManager configManager;
    private CounterManager counterManager;
    private Logger log = Logger.getLogger(CounterController.class);

    /**??
    */

    public @ResponseBody(datatype = "json") String statisticOperCounterImmediately() {
        Calendar today = Calendar.getInstance();
        String todayTime = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        String week = String.valueOf(today.get(Calendar.WEEK_OF_YEAR));
        week = todayTime.substring(0, 4) + "-" + week;
        Calendar startDate = Calendar.getInstance();
        int offset = startDate.get(Calendar.DAY_OF_WEEK);
        startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
        String startTime = DateUtils.format(startDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        TransactionManager tm = new TransactionManager();
        try {
            tm.begin(TransactionManager.RW_TRANSACTION);
            //
            counterManager.deleteOperCounterByWeek(week);
            counterManager.staticOperCounterByWeek(startTime, todayTime, week);

            //
            counterManager.deleteOperCounterByDay(todayTime);
            counterManager.staticOperCounterByDay(todayTime);

            //
            counterManager.deleteOperCounterByMonth(todayTime.substring(0, 7));
            counterManager.staticOperCounterByMonth(todayTime.substring(0, 7));

            //

            counterManager.deleteOperCounterByYear(todayTime.substring(0, 4));
            counterManager.staticOperCounterByYear(todayTime.substring(0, 4));

            tm.commit();

            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getLocalizedMessage();
        } finally {
            tm.release();
        }
    }

    /**
     * Excel
    */
    public void downloadExcel(String time, String type, String appId, HttpServletResponse response) {

        try {
            List<OperRank> datas = counterManager.getExcelDatas(time, type, appId);
            if (null != datas && datas.size() > 0) {
                for (int i = 0; i < datas.size(); i++) {
                    int j = i + 1;
                    datas.get(i).setAppId("(" + j + ")");
                }
            }
            String colDesc = getExcelColDesc(Dictionary.titles);
            XSSFWorkbook wb = POIExcelUtil2007.createHSSFWorkbook(colDesc, datas);

            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new URLCodec().encode(time + "__" + datas.get(0).getAppName() + "__?.xlsx"));
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    public String getExcelColDesc(String[] desc) {
        List<String> colList = new ArrayList<String>();
        for (int i = 0; i < desc.length; i++) {
            colList.add(desc[i]);
        }
        return StringUtils.join(colList, ", ");
    }

    /**???
    */
    public String showOperCounterRankByWeek(
            @PagerParam(name = PagerParam.SORT, defaultvalue = "vcount") String sortKey,
            @PagerParam(name = PagerParam.DESC, defaultvalue = "false") boolean desc,
            @PagerParam(name = PagerParam.OFFSET) long offset,
            @PagerParam(name = PagerParam.PAGE_SIZE, defaultvalue = "10") int pagesize, String appId, String vtime,
            ModelMap model) throws Exception {
        if (null == vtime || "".equals(vtime)) {
            Calendar calendar = Calendar.getInstance();
            Calendar today = Calendar.getInstance();
            String todayTime = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN);
            String year = todayTime.substring(0, 4);
            int weeks = calendar.get(Calendar.WEEK_OF_YEAR);
            vtime = year + "-" + String.valueOf(weeks);
        }
        /*else{
           String year = vtime.substring(0, 4);
           String week = vtime.substring(5,7);
           vtime = year+"-"+week;
               
        }*/
        ListInfo datas = counterManager.getOperCounterRankByWeek(appId, vtime, (int) offset, pagesize);
        model.addAttribute("datas", datas);
        return "path:operCounterRankData";
    }

    /**???
    */
    public String showOperCounterRankByDay(
            @PagerParam(name = PagerParam.SORT, defaultvalue = "vcount") String sortKey,
            @PagerParam(name = PagerParam.DESC, defaultvalue = "false") boolean desc,
            @PagerParam(name = PagerParam.OFFSET) long offset,
            @PagerParam(name = PagerParam.PAGE_SIZE, defaultvalue = "10") int pagesize, String appId, String vtime,
            ModelMap model) throws Exception {
        if (null == vtime || "".equals(vtime)) {
            Calendar calendar = Calendar.getInstance();
            vtime = DateUtils.format(calendar.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }
        ListInfo datas = counterManager.getOperCounterRankByDay(appId, vtime, (int) offset, pagesize);
        model.addAttribute("datas", datas);
        return "path:operCounterRankData";
    }

    /**???
    */
    public String showOperCounterRankByMonth(
            @PagerParam(name = PagerParam.SORT, defaultvalue = "vcount") String sortKey,
            @PagerParam(name = PagerParam.DESC, defaultvalue = "false") boolean desc,
            @PagerParam(name = PagerParam.OFFSET) long offset,
            @PagerParam(name = PagerParam.PAGE_SIZE, defaultvalue = "10") int pagesize, String appId, String month,
            String year, ModelMap model) throws Exception {

        if (null == month || "".equals(month)) {
            Calendar calendar = Calendar.getInstance();
            month = DateUtils.format(calendar.getTime(), DateUtils.ISO8601_DATE_PATTERN).substring(5, 7);
        }
        if (null == year || "".equals(year)) {
            Calendar calendar = Calendar.getInstance();
            year = DateUtils.format(calendar.getTime(), DateUtils.ISO8601_DATE_PATTERN).substring(0, 4);
        }
        String vtime = year.concat("-").concat(month);
        ListInfo datas = counterManager.getOperCounterRankByMonth(appId, vtime, (int) offset, pagesize);
        model.addAttribute("datas", datas);
        return "path:operCounterRankData";
    }

    /**???
    */
    public String showOperCounterRankByYear(
            @PagerParam(name = PagerParam.SORT, defaultvalue = "vcount") String sortKey,
            @PagerParam(name = PagerParam.DESC, defaultvalue = "false") boolean desc,
            @PagerParam(name = PagerParam.OFFSET) long offset,
            @PagerParam(name = PagerParam.PAGE_SIZE, defaultvalue = "10") int pagesize, String appId, String vtime,
            ModelMap model) throws Exception {

        if (null == vtime || "".equals(vtime)) {
            Calendar calendar = Calendar.getInstance();
            vtime = DateUtils.format(calendar.getTime(), DateUtils.ISO8601_DATE_PATTERN).substring(0, 4);
        }
        ListInfo datas = counterManager.getOperCounterRankByYear(appId, vtime, (int) offset, pagesize);
        model.addAttribute("datas", datas);
        return "path:operCounterRankData";
    }

    /**
     * ?
     */

    public String checkBrowserDetail(String browserId, ModelMap model) throws SQLException {

        List<BrowserCounter> browserCounterDetail = counterManager.getBrowserCounterDetail(browserId);
        model.addAttribute("browserCounterDetail", browserCounterDetail);
        return "path:browserCounterDetail";
    }

    /**
     * ?
     */

    public String checkOperateDetail(String operateId, ModelMap model) throws SQLException {

        List<OperateCounter> operateCounterDetail = counterManager.getOperateCounterDetail(operateId);
        model.addAttribute("operateCounterDetail", operateCounterDetail);
        return "path:operateCounterDetail";
    }

    /**
     * ?
     * @param paramCounter ?
     * @param enable ??
     * @param request HttpServletRequest
     * @return long ? 
     * @throws Exception
     */
    public @ResponseBody(datatype = "jsonp") long operateCounter(OperateCounter paramCounter, boolean enable,
            HttpServletRequest request) throws Exception {

        paramCounter.setOperateId(UUID.randomUUID().toString());

        String appName = paramCounter.getAppName();
        String moduleName = paramCounter.getModuleName();
        String moduleCode = paramCounter.getModuleCode();
        String modulePath = paramCounter.getModulePath();
        String operator = paramCounter.getOperator();
        if (null != operator && !"".equals(operator)) {
            paramCounter.setOperator(URLDecoder.decode(operator, "UTF-8"));
        } else {
            paramCounter.setOperator(AccessControl.getAccessControl().getUserAccount());
        }

        String pageName = paramCounter.getPageName();
        String operContent = paramCounter.getOperContent();

        paramCounter.setModulePath(StringUtil.isEmpty(modulePath) ? null : URLDecoder.decode(modulePath, "UTF-8"));
        paramCounter.setAppName(StringUtil.isEmpty(appName) ? null : URLDecoder.decode(appName, "UTF-8"));
        paramCounter.setModuleName(StringUtil.isEmpty(moduleName) ? null : URLDecoder.decode(moduleName, "UTF-8"));
        paramCounter.setPageName(StringUtil.isEmpty(pageName) ? null : URLDecoder.decode(pageName, "UTF-8"));
        paramCounter
                .setOperContent(StringUtil.isEmpty(operContent) ? null : URLDecoder.decode(operContent, "UTF-8"));
        Module module = configManager.checkAppModule(paramCounter.getAppName(), paramCounter.getModuleName(),
                paramCounter.getModuleCode(), paramCounter.getModulePath());// appId  moduleId
        paramCounter.setAppId(Integer.parseInt(module.getAppId()));
        paramCounter.setModuleId(Integer.parseInt(module.getModuleId()));
        paramCounter.setOperateIp(com.frameworkset.util.StringUtil.getClientIP(request));

        paramCounter.setPageURL(paramCounter.getPageURL());
        //?
        String userAgent = request.getHeader("User-Agent");
        for (String agent : userAgent.split(";")) {
            for (String browser : browserTypeSet) {
                if (agent.indexOf(browser) > 0) {
                    paramCounter.setBrowserType(agent.substring(agent.indexOf(browser)).replaceAll("/", " "));
                    break;
                }
            }
        }
        //??url
        paramCounter.setReferer(request.getHeader("Referer"));
        //???
        TransactionManager tm = new TransactionManager();
        try {
            tm.begin(TransactionManager.RW_TRANSACTION);
            counterManager.incrementOperateCounter(paramCounter);//?
            long ret = 0;
            /*if (enable) {
               ret = counterManager.getBrowserCount(paramCounter.getSiteId());
            }*/
            tm.commit();
            return ret;
        } finally {
            tm.release();
        }
    }

    /**
     * ??showOperateCounterList
     * 
     * @param sortKey ?
     * @param desc ??
     * @param offset ???
     * @param pagesize ???
     * @param counter ?
     * @param startTime 
     * @param endTime ?
     * @param model 
     * @return String
     * 
     */
    public String showOperateCounterList(
            @PagerParam(name = PagerParam.SORT, defaultvalue = "browserTime") String sortKey,
            @PagerParam(name = PagerParam.DESC, defaultvalue = "false") boolean desc,
            @PagerParam(name = PagerParam.OFFSET) long offset,
            @PagerParam(name = PagerParam.PAGE_SIZE, defaultvalue = "10") int pagesize, OperateCounter counter,
            Timestamp startTime, Timestamp endTime, ModelMap model) throws Exception {

        ListInfo operateCounterDataList = counterManager.getOperateCounterList(counter, startTime, endTime,
                (int) offset, pagesize);
        model.addAttribute("operateCounterDataList", operateCounterDataList);

        if (operateCounterDataList.getSize() > 0) {
        }
        return "path:showoperateCounterList";
    }

    /**
     * ? 
     * @return String
     */
    //????
    @SuppressWarnings("unchecked")
    public @ResponseBody(datatype = "json") List<Module> getModuleBySiteId(String appId) throws Exception {
        return counterManager.getAllModulesOfApp(appId);
    }

    //????
    @SuppressWarnings("unchecked")
    public @ResponseBody(datatype = "json") List<App> getAllApp(HttpServletRequest request,
            HttpServletResponse response) throws SQLException {
        com.frameworkset.platform.security.AccessControl control = com.frameworkset.platform.security.AccessControl
                .getInstance();
        control.checkAccess(request, response, false);
        String userId = control.getUserID();
        /*if("1".equals(userId)){
           return counterManager.getAdminApp(userId);
        }else{
           return counterManager.getApp(userId);
        }*/
        return counterManager.getAdminApp("1");
    }

    public String index() {
        return "path:index";
    }

    //??
    public String attachIndex() {
        return "path:attachindex";
    }

    //???
    public String operateIndex() {
        return "path:operateindex";
    }

    /**
     * 
     * @param paramCounter ?
     * @param enable ??
     * @param request HttpServletRequest
     * @return long  
     * @throws Exception
     */
    public @ResponseBody(datatype = "jsonp") long videoHitsCount(VideoHitsCounter paramCounter, boolean enable,
            HttpServletRequest request) throws Exception {

        paramCounter.setHitId(UUID.randomUUID().toString());

        String siteName = paramCounter.getSiteName();
        String channelName = paramCounter.getChannelName();
        String docName = paramCounter.getDocName();

        paramCounter.setSiteName(StringUtil.isEmpty(siteName) ? null : URLDecoder.decode(siteName, "UTF-8"));
        paramCounter
                .setChannelName(StringUtil.isEmpty(channelName) ? null : URLDecoder.decode(channelName, "UTF-8"));
        paramCounter.setDocName(StringUtil.isEmpty(docName) ? null : URLDecoder.decode(docName, "UTF-8"));

        paramCounter.setHitIP(com.frameworkset.util.StringUtil.getClientIP(request));
        paramCounter.setHitUser(AccessControl.getAccessControl().getUserAccount());
        paramCounter.setReferer(request.getHeader("Referer"));

        TransactionManager tm = new TransactionManager();
        try {
            tm.begin(TransactionManager.RW_TRANSACTION);
            counterManager.incrementVideoHitsCounter(paramCounter);
            long ret = 0;
            if (enable) {
                ret = counterManager.getVideoHitsCount(paramCounter.getSiteId(), paramCounter.getChannelId(),
                        paramCounter.getDocId());
            }
            tm.commit();
            return ret;
        } finally {
            tm.release();
        }
    }

    /**
     * ?
     * @param paramCounter ?
     * @param enable ??
     * @param request HttpServletRequest
     * @return long ? 
     * @throws Exception
     */
    public @ResponseBody(datatype = "jsonp") long browserCounter(BrowserCounter paramCounter, boolean enable,
            HttpServletRequest request) throws Exception {
        paramCounter.setBrowserId(UUID.randomUUID().toString());

        String siteName = paramCounter.getSiteName();
        String channelName = paramCounter.getChannelName();
        String docName = paramCounter.getDocName();
        String moduleCode = paramCounter.getModuleCode();
        String modulePath = paramCounter.getModulePath();
        paramCounter.setModuleCode(StringUtil.isEmpty(moduleCode) ? null : URLDecoder.decode(moduleCode, "UTF-8"));
        paramCounter.setModulePath(StringUtil.isEmpty(modulePath) ? null : URLDecoder.decode(modulePath, "UTF-8"));

        paramCounter.setSiteName(StringUtil.isEmpty(siteName) ? null : URLDecoder.decode(siteName, "UTF-8"));
        paramCounter
                .setChannelName(StringUtil.isEmpty(channelName) ? null : URLDecoder.decode(channelName, "UTF-8"));
        paramCounter.setDocName(StringUtil.isEmpty(docName) ? null : URLDecoder.decode(docName, "UTF-8"));
        Module module = configManager.checkAppModule(paramCounter.getSiteName(), paramCounter.getChannelName(),
                paramCounter.getModuleCode(), paramCounter.getModulePath());// appId  moduleId
        paramCounter.setSiteId(Integer.parseInt(module.getAppId()));
        paramCounter.setChannelId(Integer.parseInt(module.getModuleId()));
        paramCounter.setBrowserIp(com.frameworkset.util.StringUtil.getClientIP(request));
        paramCounter.setBrowserUser(AccessControl.getAccessControl().getUserAccount());
        paramCounter.setPageURL(paramCounter.getPageURL());
        //?
        String userAgent = request.getHeader("User-Agent");
        for (String agent : userAgent.split(";")) {
            for (String browser : browserTypeSet) {
                if (agent.indexOf(browser) > 0) {
                    paramCounter.setBrowserType(agent.substring(agent.indexOf(browser)).replaceAll("/", " "));
                    break;
                }
            }
        }
        //??url
        paramCounter.setReferer(request.getHeader("Referer"));
        //???
        TransactionManager tm = new TransactionManager();
        try {
            tm.begin(TransactionManager.RW_TRANSACTION);
            counterManager.incrementBrowserCounter(paramCounter);//?
            long ret = 0;
            if (enable) {
                ret = counterManager.getBrowserCount(paramCounter.getSiteId());
            }
            tm.commit();
            return ret;
        } finally {
            tm.release();
        }
    }

    /**
     * ??
     * 
     * @param sortKey ?
     * @param desc ??
     * @param offset ???
     * @param pagesize ???
     * @param counter ?
     * @param startTime 
     * @param endTime ?
     * @param model 
     * @return String
     */
    public String showBrowserCounterList(
            @PagerParam(name = PagerParam.SORT, defaultvalue = "browserTime") String sortKey,
            @PagerParam(name = PagerParam.DESC, defaultvalue = "false") boolean desc,
            @PagerParam(name = PagerParam.OFFSET) long offset,
            @PagerParam(name = PagerParam.PAGE_SIZE, defaultvalue = "10") int pagesize, BrowserCounter counter,
            Timestamp startTime, Timestamp endTime, ModelMap model) throws Exception {

        ListInfo browserCounterDataList = counterManager.getBrowserCounterList(counter, startTime, endTime,
                (int) offset, pagesize);

        model.addAttribute("browserCounterDataList", browserCounterDataList);

        return "path:showBrowserCounterList";
    }

    /**
     * ??
     * @param type : yesterday:
     * @return String
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public @ResponseBody String showBrowserCounterHourDistribute(int siteId, String type, String startTime)
            throws Exception {

        String caption = "??";
        String subCaption = "";

        Calendar calendar = Calendar.getInstance();
        if ("yesterday".equals(type)) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);

            subCaption = "";
        }

        if (StringUtil.isEmpty(startTime)) {
            startTime = DateUtils.format(calendar.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }

        List<HashMap> browserCounterDayDistribute = counterManager.getBrowserCounterHourDistribute(siteId,
                startTime);

        StringBuilder xml = new StringBuilder("<chart caption='").append(caption).append("' subCaption='")
                .append(subCaption)
                .append("' yMaxValue='100' bgColor='406181, 6DA5DB'  bgAlpha='100' baseFontColor='FFFFFF' canvasBgAlpha='0' canvasBorderColor='FFFFFF' divLineColor='FFFFFF' divLineAlpha='100' numVDivlines='10' vDivLineisDashed='1' showAlternateVGridColor='1' lineColor='BBDA00' anchorRadius='4' anchorBgColor='BBDA00' anchorBorderColor='FFFFFF' anchorBorderThickness='2' showValues='0' toolTipBgColor='406181' toolTipBorderColor='406181' alternateHGridAlpha='5'>");

        if (!CollectionUtils.isEmpty(browserCounterDayDistribute)) {
            for (int i = 1; i <= 24; i++) {

                int vhour = i;
                int vcount = 0;

                for (HashMap map : browserCounterDayDistribute) {
                    int time = Integer.parseInt(map.get("VHOUR").toString());

                    if (time == i) {
                        vcount = Integer.parseInt(map.get("VCOUNT").toString());

                        break;
                    }
                }

                xml.append("<set label='").append(vhour).append(":00'").append(" value='").append(vcount)
                        .append("' />");
            }
        }

        xml.append(
                "<styles><definition><style name='LineShadow' type='shadow' color='333333' distance='6'/></definition><application><apply toObject='DATAPLOT' styles='LineShadow' /></application></styles></chart> ");
        return xml.toString();
    }

    /**
     * ?
     * @param type week:7days:7month:30days:30
     * @return String
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public @ResponseBody String showBrowserCounterDayDistribute(int siteId, String type, String startTime,
            String endTime) throws Exception {

        String caption = "?";
        String subCaption = "";

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        int addDay = 0;

        if ("week".equals(type)) {
            int offset = startDate.get(Calendar.DAY_OF_WEEK);
            startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
            endDate = (Calendar) startDate.clone();
            endDate.add(Calendar.DAY_OF_MONTH, 6);

            addDay = 6;

            subCaption = "";
        } else if ("7days".equals(type)) {
            startDate.add(Calendar.DAY_OF_MONTH, -6);

            addDay = 6;

            subCaption = "7";
        } else if ("month".equals(type)) {
            int offset = startDate.get(Calendar.DAY_OF_MONTH);
            startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
            endDate = (Calendar) startDate.clone();
            endDate.add(Calendar.MONTH, 1);
            endDate.add(Calendar.DAY_OF_MONTH, -1);

            addDay = startDate.getActualMaximum(Calendar.DAY_OF_MONTH)
                    - startDate.getActualMinimum(Calendar.DAY_OF_MONTH);

            subCaption = "";
        } else if ("30days".equals(type)) {
            startDate.add(Calendar.DAY_OF_MONTH, -29);

            addDay = 29;

            subCaption = "30";
        }

        List<Calendar> calendarList = new ArrayList<Calendar>();
        for (int i = 0; i <= addDay; i++) {
            Calendar tempStartDate = (Calendar) startDate.clone();
            tempStartDate.add(Calendar.DAY_OF_MONTH, i);
            calendarList.add(tempStartDate);
        }

        if (StringUtil.isEmpty(startTime)) {
            startTime = DateUtils.format(startDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }
        if (StringUtil.isEmpty(endTime)) {
            endTime = DateUtils.format(endDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }

        List<HashMap> browserCounterDayDistribute = counterManager.getBrowserCounterDayDistribute(siteId, startTime,
                endTime);

        StringBuilder xml = new StringBuilder("<chart caption='").append(caption).append("' subCaption='")
                .append(subCaption)
                .append("' yMaxValue='100' bgColor='406181, 6DA5DB'  bgAlpha='100' baseFontColor='FFFFFF' canvasBgAlpha='0' canvasBorderColor='FFFFFF' divLineColor='FFFFFF' divLineAlpha='100' numVDivlines='10' vDivLineisDashed='1' showAlternateVGridColor='1' lineColor='BBDA00' anchorRadius='4' anchorBgColor='BBDA00' anchorBorderColor='FFFFFF' anchorBorderThickness='2' showValues='0' toolTipBgColor='406181' toolTipBorderColor='406181' alternateHGridAlpha='5'>");

        if (!CollectionUtils.isEmpty(browserCounterDayDistribute)) {

            for (Calendar calendar : calendarList) {
                int vday = calendar.get(Calendar.DAY_OF_MONTH);
                int vcount = 0;

                for (HashMap map : browserCounterDayDistribute) {
                    if (vday == Integer.parseInt(map.get("VDAY").toString())) {
                        vcount = Integer.parseInt(map.get("VCOUNT").toString());

                        break;
                    }
                }

                xml.append("<set label='").append(vday).append("' value='").append(vcount).append("' />");
            }

            xml.append(
                    "<styles><definition><style name='LineShadow' type='shadow' color='333333' distance='6'/></definition><application><apply toObject='DATAPLOT' styles='LineShadow' /></application></styles></chart> ");
        }
        return xml.toString();
    }

    /**
     * ?
     * @param type : yesterday:
     * @return String 
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public @ResponseBody String showBrowserTypeDistributeToday(int siteId, String type, String startTime)
            throws Exception {

        String caption = "?";
        String subCaption = "";

        Calendar calendar = Calendar.getInstance();
        if ("yesterday".equals(type)) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);

            subCaption = "";
        }

        if (StringUtil.isEmpty(startTime)) {
            startTime = DateUtils.format(calendar.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }

        List<HashMap> browserTypeDayDistribute = counterManager.getBrowserTypeDayDistribute(siteId, startTime);

        StringBuilder xml = new StringBuilder("<chart caption='").append(caption).append("' subCaption='")
                .append(subCaption)
                .append("' showLabels='0' showValues='0' showLegend='1'  legendPosition='RIGHT' chartrightmargin='40' bgcolor='ECF5FF' bgalpha='70' bordercolor='C6D2DF' basefontcolor='2F2F2F' basefontsize='11' showpercentvalues='1' bgratio='0' startingangle='200' animation='1'>");

        if (!CollectionUtils.isEmpty(browserTypeDayDistribute)) {
            for (HashMap map : browserTypeDayDistribute) {
                int vcount = Integer.parseInt(map.get("VCOUNT").toString());
                String browserType = map.get("VBROWSERTYPE").toString();

                xml.append(" <set value='").append(vcount).append("' label='").append(browserType).append("'/>");
            }
        }

        xml.append(" </chart>");
        //System.out.println("xml----------------------"+xml.toString());
        return xml.toString();
    }

    /**
     * ? 
     * @param type week:7days:7month:30days:30
     * @return String 
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public @ResponseBody String showBrowserTypeDayDistribute(int siteId, String type, String startTime,
            String endTime) throws Exception {

        String caption = "?";
        String subCaption = "";

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        if ("week".equals(type)) {
            int offset = startDate.get(Calendar.DAY_OF_WEEK);
            startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
            endDate = (Calendar) startDate.clone();
            endDate.add(Calendar.DAY_OF_MONTH, 6);

            subCaption = "";
        } else if ("7days".equals(type)) {
            startDate.add(Calendar.DAY_OF_MONTH, -6);

            subCaption = "7";
        } else if ("month".equals(type)) {
            int offset = startDate.get(Calendar.DAY_OF_MONTH);
            startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
            endDate = (Calendar) startDate.clone();
            endDate.add(Calendar.MONTH, 1);
            endDate.add(Calendar.DAY_OF_MONTH, -1);

            subCaption = "";
        } else if ("30days".equals(type)) {
            startDate.add(Calendar.DAY_OF_MONTH, -30);

            subCaption = "30";
        }

        if (StringUtil.isEmpty(startTime)) {
            startTime = DateUtils.format(startDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }
        if (StringUtil.isEmpty(endTime)) {
            endTime = DateUtils.format(endDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }

        List<HashMap> browserTypeDayDistribute = counterManager.getBrowserTypeDayDistribute(siteId, startTime,
                endTime);

        StringBuilder xml = new StringBuilder("<chart caption='").append(caption).append("' subCaption='")
                .append(subCaption)
                .append("' showLabels='0' showValues='0' showLegend='1'  legendPosition='RIGHT' chartrightmargin='40' bgcolor='ECF5FF' bgalpha='70' bordercolor='C6D2DF' basefontcolor='2F2F2F' basefontsize='11' showpercentvalues='1' bgratio='0' startingangle='200' animation='1'>");

        if (!CollectionUtils.isEmpty(browserTypeDayDistribute)) {
            for (HashMap map : browserTypeDayDistribute) {
                int vcount = Integer.parseInt(map.get("VCOUNT").toString());
                String browserType = map.get("VBROWSERTYPE").toString();
                System.out.println();
                xml.append(" <set value='").append(vcount).append("' label='").append(browserType).append("'/>");
            }
        }

        xml.append(" </chart>");
        // System.out.println("xml--------------------------------"+xml.toString());
        return xml.toString();
    }

    /**
     * ?IP?
     * @param type : yesterday:
     * @return String 
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public @ResponseBody String showBrowserIPDistributeToday(int siteId, String type, String startTime)
            throws Exception {

        String caption = "?IP?";
        String subCaption = "";

        Calendar calendar = Calendar.getInstance();
        if ("yesterday".equals(type)) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);

            subCaption = "";
        }

        if (StringUtil.isEmpty(startTime)) {
            startTime = DateUtils.format(calendar.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }

        List<HashMap> browserIPDayDistribute = counterManager.getBrowserIPDayDistribute(siteId, startTime);

        StringBuilder xml = new StringBuilder("<chart caption='").append(caption).append("' subCaption='")
                .append(subCaption)
                .append("' showLabels='0' showValues='0' showLegend='1'  legendPosition='RIGHT' chartrightmargin='40' bgcolor='ECF5FF' bgalpha='70' bordercolor='C6D2DF' basefontcolor='2F2F2F' basefontsize='11' showpercentvalues='1' bgratio='0' startingangle='200' animation='1'>");

        if (!CollectionUtils.isEmpty(browserIPDayDistribute)) {
            for (HashMap map : browserIPDayDistribute) {
                int vcount = Integer.parseInt(map.get("VCOUNT").toString());
                String browserType = map.get("VBROWSERIP").toString();

                xml.append(" <set value='").append(vcount).append("' label='").append(browserType).append(".**")
                        .append("'/>");
            }
        }

        xml.append(" </chart>");

        return xml.toString();
    }

    /**
     * ?IP? 
     * @param type week:7days:7month:30days:30
     * @return String 
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public @ResponseBody String showBrowserIPDayDistribute(int siteId, String type, String startTime,
            String endTime) throws Exception {

        String caption = "?IP?";
        String subCaption = "";

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        if ("week".equals(type)) {
            int offset = startDate.get(Calendar.DAY_OF_WEEK);
            startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
            endDate = (Calendar) startDate.clone();
            endDate.add(Calendar.DAY_OF_MONTH, 6);

            subCaption = "";
        } else if ("7days".equals(type)) {
            startDate.add(Calendar.DAY_OF_MONTH, -6);

            subCaption = "7";
        } else if ("month".equals(type)) {
            int offset = startDate.get(Calendar.DAY_OF_MONTH);
            startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
            endDate = (Calendar) startDate.clone();
            endDate.add(Calendar.MONTH, 1);
            endDate.add(Calendar.DAY_OF_MONTH, -1);

            subCaption = "";
        } else if ("30days".equals(type)) {
            startDate.add(Calendar.DAY_OF_MONTH, -30);

            subCaption = "30";
        }

        if (StringUtil.isEmpty(startTime)) {
            startTime = DateUtils.format(startDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }
        if (StringUtil.isEmpty(endTime)) {
            endTime = DateUtils.format(endDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }

        List<HashMap> browserIPDayDistribute = counterManager.getBrowserIPDayDistribute(siteId, startTime, endTime);

        StringBuilder xml = new StringBuilder("<chart caption='").append(caption).append("' subCaption='")
                .append(subCaption)
                .append("' showLabels='0' showValues='0' showLegend='1'  legendPosition='RIGHT' chartrightmargin='40' bgcolor='ECF5FF' bgalpha='70' bordercolor='C6D2DF' basefontcolor='2F2F2F' basefontsize='11' showpercentvalues='1' bgratio='0' startingangle='200' animation='1'>");

        if (!CollectionUtils.isEmpty(browserIPDayDistribute)) {
            for (HashMap map : browserIPDayDistribute) {
                int vcount = Integer.parseInt(map.get("VCOUNT").toString());
                String browserType = map.get("VBROWSERIP").toString();

                xml.append(" <set value='").append(vcount).append("' label='").append(browserType).append(".**")
                        .append("'/>");
            }
        }

        xml.append(" </chart>");

        return xml.toString();
    }

    /**
     * ???
     * 
     * @param sortKey ?
     * @param desc ??
     * @param offset ???
     * @param pagesize ???
     * @param counter ?
     * @param model 
     * @return String
     */
    public String showPageBrowserCounterGatherList(
            @PagerParam(name = PagerParam.SORT, defaultvalue = "browserTime") String sortKey,
            @PagerParam(name = PagerParam.DESC, defaultvalue = "false") boolean desc,
            @PagerParam(name = PagerParam.OFFSET) long offset,
            @PagerParam(name = PagerParam.PAGE_SIZE, defaultvalue = "10") int pagesize, BrowserCounter counter,
            String startTime, String endTime, ModelMap model) throws Exception {

        ListInfo pageBrowserCounterGatherDataList = counterManager.getPageBrowserCounterGatherList(counter,
                startTime, endTime, (int) offset, pagesize);

        model.addAttribute("pageBrowserCounterGatherDataList", pageBrowserCounterGatherDataList);

        return "path:showPageBrowserCounterGatherList";
    }

    /**
     * @param siteId
     * @param type
     * @param model
     * @return
     */
    public String showBrowserCounterDistribute(int siteId, String type, String startTime, String endTime,
            ModelMap model) throws Exception {

        if (!"custom".equals(type)) {

            Calendar startDate = Calendar.getInstance();
            Calendar endDate = Calendar.getInstance();

            if ("yesterday".equals(type)) {
                startDate.add(Calendar.DAY_OF_MONTH, -1);
                endDate = (Calendar) startDate.clone();
            } else if ("week".equals(type)) {
                int offset = startDate.get(Calendar.DAY_OF_WEEK);
                startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
                endDate = (Calendar) startDate.clone();
                endDate.add(Calendar.DAY_OF_MONTH, 6);
            } else if ("7days".equals(type)) {
                startDate.add(Calendar.DAY_OF_MONTH, -6);
            } else if ("month".equals(type)) {
                int offset = startDate.get(Calendar.DAY_OF_MONTH);
                startDate.add(Calendar.DAY_OF_MONTH, offset - (offset * 2 - 1));
                endDate = (Calendar) startDate.clone();
                endDate.add(Calendar.MONTH, 1);
                endDate.add(Calendar.DAY_OF_MONTH, -1);
            } else if ("30days".equals(type)) {
                startDate.add(Calendar.DAY_OF_MONTH, -30);
            }

            startTime = DateUtils.format(startDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
            endTime = DateUtils.format(endDate.getTime(), DateUtils.ISO8601_DATE_PATTERN);
        }

        // ??
        List<BrowserVisitInfo> browserVisitInfoList = counterManager.getBrowserVisitInfo(siteId, startTime,
                endTime);

        if (!CollectionUtils.isEmpty(browserVisitInfoList)) {
            if ("week".equals(type) || "7days".equals(type) || "month".equals(type) || "30days".equals(type)) {
                browserVisitInfoList.remove(1);
                browserVisitInfoList.remove(1);
            }
        }

        model.addAttribute("browserVisitInfoList", browserVisitInfoList);

        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime", endTime);

        model.addAttribute("siteId", siteId);
        model.addAttribute("type", type);

        String browserCounterForwordPage = "showBrowserCounterDayDistribute.page";
        String browserTypeForwordPage = "showBrowserTypeDayDistribute.page";
        String browserIPForwordPage = "showBrowserIPDayDistribute.page";

        if ("today".equals(type) || "yesterday".equals(type) || "custom".equals(type)) {
            browserCounterForwordPage = "showBrowserCounterHourDistribute.page";
            browserTypeForwordPage = "showBrowserTypeDistributeToday.page";
            browserIPForwordPage = "showBrowserIPDistributeToday.page";
        }

        model.addAttribute("browserCounterForwordPage", browserCounterForwordPage);
        model.addAttribute("browserTypeForwordPage", browserTypeForwordPage);
        model.addAttribute("browserIPForwordPage", browserIPForwordPage);

        return "path:showBrowserCounterDistribute";
    }

    /**
     * @param siteId
     * @return
     * @throws Exception
     */
    public @ResponseBody(datatype = "json") long getBrowserCount(int siteId) throws Exception {
        return counterManager.getBrowserCount(siteId);
    }

    /**
     * @param siteId
     * @return
     */
    public @ResponseBody(datatype = "json") String statisticImmediately(int siteId) {

        TransactionManager tm = new TransactionManager();
        try {
            tm.begin(TransactionManager.RW_TRANSACTION);

            counterManager.deleteStatisticBrowserCounter(siteId);
            counterManager.deleteStatisticBrowserType(siteId);
            counterManager.deleteStatisticBrowserIP(siteId);

            counterManager.statisticBrowserCounter(null, null, siteId);
            counterManager.statisticBrowserType(null, null, siteId);
            counterManager.statisticBrowserIP(null, null, siteId);

            tm.commit();

            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getLocalizedMessage();
        } finally {
            tm.release();
        }
    }

    //?---??
    @SuppressWarnings("rawtypes")
    public @ResponseBody String historyCompare(String tableName, String appId, String compareType, String startTime,
            String endTime) {
        try {
            List<OperRank> datas = new ArrayList<OperRank>();

            datas = counterManager.getOperRankForCompareByDay(appId, startTime, endTime, tableName);
            List<String> timeNodes = counterManager.getTimeNodes(startTime, endTime, tableName);
            List<String> moduleNodes = counterManager.getModuleNodes(appId, startTime, endTime, tableName);
            String caption = "";
            if ("count".equals(compareType)) {
                caption = "?";
            } else {
                caption = "?";
            }
            String dataXML = "<chart caption='" + caption + "' subcaption='' "
                    + "lineThickness='1' showValues='0' formatNumberScale='0' anchorRadius='2'   "
                    + "divLineAlpha='20' divLineColor='CC3300' divLineIsDashed='1' showAlternateHGridColor='1' "
                    + "alternateHGridColor='CC3300' shadowAlpha='40' labelStep='2' "
                    + "numvdivlines='5' chartRightMargin='35' bgColor='FFFFFF,CC3300' bgAngle='270' bgAlpha='10,10' "
                    + "alternateHGridAlpha='5'  legendPosition ='RIGHT '>";
            /**
            */
            String categories = "<categories>";
            for (String timeNode : timeNodes) {//
                categories += "<category label='" + timeNode + "' />";
            }
            categories += "</categories>";
            dataXML = dataXML + categories;
            for (String moduleNode : moduleNodes) {//?
                String dataset = "<dataset seriesName='" + moduleNode + "'>";
                for (String timeNode : timeNodes) {
                    boolean dupli = false;
                    for (OperRank bean : datas) {
                        if (moduleNode.equals(bean.getModuleName()) && timeNode.equals(bean.getVtime())) {//??
                            if ("count".equals(compareType)) {
                                dataset += "<set value='" + bean.getVcount() + "' />";
                            } else {
                                dataset += "<set value='" + bean.getVcount() + "' />";
                            }
                            datas.remove(bean);
                            dupli = true;
                            break;
                        }
                    }
                    if (!dupli) {
                        dataset += "<set value='0' />";
                    }
                }
                dataset += "</dataset>";
                dataXML = dataXML + dataset;
            }
            dataXML += "</chart>";
            return dataXML;
        } catch (SQLException e) {
            return e.getSQLState();
        }

    }

    @SuppressWarnings("rawtypes")
    public @ResponseBody String operCountCompare(String type, String appId, String time) throws Exception {
        if ("".equals(appId) || null == appId) {
            return null;
        }
        String tableName = "";
        float divisor = 1;
        if ("day".equals(type)) {
            if ("".equals(time) || null == time) {
                Calendar today = Calendar.getInstance();
                time = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN);
            }

            tableName = "TD_LOG_OPERSTATIC_BYDAY";
            divisor = 30;

        } else if ("week".equals(type)) {

            if ("".equals(time) || null == time) {
                Calendar today = Calendar.getInstance();
                String todayTime = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN);
                String week = String.valueOf(today.get(Calendar.WEEK_OF_YEAR));
                time = todayTime.substring(0, 4) + "-" + week;
            }

            tableName = "TD_LOG_OPERSTATIC_BYWEEK";
            divisor = 4;

        } else if ("month".equals(type)) {
            if ("".equals(time) || null == time) {
                Calendar today = Calendar.getInstance();
                time = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN).substring(0, 7);
            }

            tableName = "TD_LOG_OPERSTATIC_BYMONTH";
            divisor = 1;
        } else if ("year".equals(type)) {
            if ("".equals(time) || null == time) {
                Calendar today = Calendar.getInstance();
                time = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN).substring(0, 4);
            }
            tableName = "TD_LOG_OPERSTATIC_BYYEAR";
            divisor = (float) 0.083;
        }
        List<OperChart> datas = counterManager.getOperChartCount(appId, time, tableName, divisor);
        String dataXML = "<chart xAxisName = '??' yAxisName='' showValues='0'>";
        dataXML += "<dataset label='' value='' />";
        String categories = "<categories>";
        String datasetSim = "<dataset seriesName=''>";
        String datasetCom = "<dataset seriesName=''>";
        if (datas.size() > 0) {
            for (OperChart bean : datas) {
                categories += "<category label=' " + bean.getModuleName() + " ' />";
                datasetSim += "<set value='" + bean.getVcount() + "' />";
                datasetCom += "<set value='" + bean.getEstimateOper() + "' />";
            }
        }
        categories += "</categories>";
        datasetSim += "</dataset>";
        datasetCom += "</dataset>";
        dataXML += categories + datasetSim + datasetCom;
        dataXML += "</chart>";
        return dataXML;

    }

    @SuppressWarnings("rawtypes")
    public @ResponseBody String operUserCompare(String type, String appId, String time) throws Exception {
        if ("".equals(appId) || null == appId) {
            return null;
        }
        String tableName = "";
        float divisor = 1;
        if ("day".equals(type)) {
            if ("".equals(time) || null == time) {
                Calendar today = Calendar.getInstance();
                time = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN);
            }
            tableName = "TD_LOG_OPERSTATIC_BYDAY";
            divisor = 30;

        } else if ("week".equals(type)) {
            if ("".equals(time) || null == time) {
                Calendar today = Calendar.getInstance();
                String todayTime = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN);
                String week = String.valueOf(today.get(Calendar.WEEK_OF_YEAR));
                time = todayTime.substring(0, 4) + "-" + week;
            }
            tableName = "TD_LOG_OPERSTATIC_BYWEEK";
            divisor = 4;
        } else if ("month".equals(type)) {
            if ("".equals(time) || null == time) {
                Calendar today = Calendar.getInstance();
                time = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN).substring(0, 7);
            }
            divisor = (float) 0.083;
            tableName = "TD_LOG_OPERSTATIC_BYMONTH";
        } else if ("year".equals(type)) {
            if ("".equals(time) || null == time) {
                Calendar today = Calendar.getInstance();
                time = DateUtils.format(today.getTime(), DateUtils.ISO8601_DATE_PATTERN).substring(0, 4);
            }
            tableName = "TD_LOG_OPERSTATIC_BYYEAR";
        }
        List<OperChart> datas = counterManager.getOperChartUser(appId, time, tableName, divisor);
        String dataXML = "<chart xAxisName = '??' yAxisName='' showValues='0'>";
        dataXML += "<dataset label='' value='' />";
        String categories = "<categories>";
        String datasetSim = "<dataset seriesName=''>";
        String datasetCom = "<dataset seriesName=''>";
        if (datas.size() > 0) {
            for (OperChart bean : datas) {
                categories += "<category label=' " + bean.getModuleName() + " ' />";
                datasetSim += "<set value='" + bean.getVcountUser() + "' />";
                datasetCom += "<set value='" + bean.getEstimateUser() + "' />";
            }
        }
        categories += "</categories>";
        datasetSim += "</dataset>";
        datasetCom += "</dataset>";
        dataXML += categories + datasetSim + datasetCom;
        dataXML += "</chart>";
        return dataXML;

    }
}