xwikistatsserviceimpl.java

来自「xwiki 源码」· Java 代码 · 共 485 行 · 第 1/2 页

JAVA
485
字号
            }
        }

    }

    private void addPageView(String docname, String action, int periodtype, XWikiHibernateStore store, XWikiContext context, VisitStats vobject) {
        DocumentStats object;
        object = new DocumentStats(docname, action, new Date(), periodtype);
        try {
            store.loadXWikiCollection(object, context, true);
        } catch (XWikiException e) {
        }
        object.incPageViews();

        // Visits are only for viewing pages
        if (docname.equals("")) {
         if ((vobject.getPageViews()==1)&&(action.equals("view"))) {
            object.incVisits();
         }
        }

        try {
            store.saveXWikiCollection(object, context, true);
        } catch (XWikiException e) {
            // Statistics should never make xwiki fail !
            e.printStackTrace();
        }
    }

    private String getReferer(XWikiContext context) {
        String referer = context.getRequest().getHeader("referer");
        try {
            URL url = new URL(referer);
            URL baseurl = context.getURL();
            if (baseurl.getHost().equals(url.getHost()))
                return null;
            return referer;
        } catch (MalformedURLException e) {
            return null;
        }
    }


    private VisitStats findVisit(XWikiContext context) {
        XWikiRequest request = context.getRequest();
        HttpSession session = request.getSession(true);
        String ip = null, ua = null;

        VisitStats vobject = (VisitStats) session.getAttribute("visitObject");

        Date nowDate = new Date();
        Cookie cookie = Util.getCookie("visitid", context);
        boolean newcookie = false;

        // If the cookie does not exist we need to set it
        if (cookie==null) {
            cookie = addCookie(context);
            newcookie = true;
        }

        if (vobject!=null) {
            // Let's verify if the session is valid
            Date endDate = vobject.getEndDate();

            // If the cookie is not the same
            if (!vobject.getCookie().equals(cookie.getValue())) {
                // Let's log a message here
                // Since the session is also maintained using a cookie
                // then there is something wrong here
                if (log.isWarnEnabled())
                  log.warn("Found visit with cookie " + vobject.getCookie() + " in session "
                           + session.getId() + " for request with cookie " + cookie.getValue());
                // And forget about this session
                vobject = null;
            }

            // If session is longer than 30 minutes we should invalidate it
            // and create a new one
            if ((nowDate.getTime()-endDate.getTime()) > 30 * 60 * 1000)
                vobject = null;
        }


        if (vobject==null) {
           if (!newcookie) {
               try {
                   vobject = findVisitByCookie(cookie.getValue(), context);
               } catch (XWikiException e) {
                   e.printStackTrace();
               }
           } else {
               try {
                   ip = request.getRemoteAddr();
                   ua = request.getHeader("User-Agent");
                   vobject = findVisitByIPUA(ip + ua, context);
               } catch (XWikiException e) {
                   e.printStackTrace();
               }

           }
        }

        if (vobject==null) {
            // we need to create the session
            if (ip==null) ip = request.getRemoteAddr();
            if (ua==null) ua = request.getHeader("User-Agent");
            String uniqueID;

            if (newcookie) {
                // We cannot yet ID the user using the cookie
                // we need to use the IP and UA
                uniqueID = ip + ua;
            } else {
             // In this case we got the cookie from the request
             // so we id the user using the cookie
              uniqueID = cookie.getValue();
            }

            vobject = new VisitStats(context.getUser(), uniqueID, cookie.getValue(),
                                     ip, ua, nowDate, XWikiStats.PERIOD_MONTH);
            vobject.setEndDate(nowDate);
        } else {
            if (!newcookie) {
             // If the cookie is not yet the unique ID we need to change that
             String uniqueID = vobject.getUniqueID();
             String oldcookie = vobject.getCookie();

             if (!uniqueID.equals(oldcookie)) {
              // We need to store the oldID so that we can remove the older entry
              // since the entry identifiers are changing
              VisitStats newvobject = (VisitStats) vobject.clone();
              newvobject.rememberOldObject(vobject);
              newvobject.setUniqueID(cookie.getValue());
              vobject = newvobject;
             }
            }

            if ((!context.getUser().equals("XWiki.XWikiGuest"))
                 &&(vobject.getUser().equals("XWiki.XWikiGuest")))
            {
              // The user has changed from guest to an authenticated user
              // We want to record this
                VisitStats newvobject = vobject;
                newvobject.rememberOldObject(vobject);
                newvobject.setName(context.getUser());
                vobject = newvobject;
            }
        }

        // Keep the visit object in the session
        session.setAttribute("visitObject", vobject);
        return vobject;
    }


    protected VisitStats findVisitByCookie(String cookie, XWikiContext context) throws XWikiException {
        XWikiHibernateStore store = context.getWiki().getHibernateStore();
        try {
        store.beginTransaction(context);
        Session session = store.getSession(context);
        Query query = session.createQuery("from VisitStats as obj where obj.cookie=:cookie and obj.endDate > :cdate order by obj.endDate desc");
        query.setString("cookie", cookie);
        Date cdate = new Date();
        cdate = new Date(cdate.getTime() - 30 * 60 * 1000);
        query.setDate("cdate", cdate);

        List solist = store.search(query, 0, 0, context);
        if (solist.size()>0)
         return (VisitStats) solist.get(0);
        else
         return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
            store.endTransaction(context, false);
            } catch (Exception e) {}
        }
    }

    protected VisitStats findVisitByIPUA(String ipua, XWikiContext context) throws XWikiException {
        XWikiHibernateStore store = context.getWiki().getHibernateStore();
        try {
        store.beginTransaction(context);
        Session session = store.getSession(context);
        Query query = session.createQuery("from VisitStats as obj where obj.uniqueID=:ipua and obj.endDate > :cdate order by obj.endDate desc");
        query.setString("ipua", ipua);
        Date cdate = new Date();
        cdate = new Date(cdate.getTime() - 30 * 60 * 1000);
        query.setDate("cdate", cdate);

        List solist = store.search(query, 0, 0, context);
        if (solist.size()>0)
         return (VisitStats) solist.get(0);
        else
         return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
            store.endTransaction(context, false);
            } catch (Exception e) {}
        }
    }

    protected Cookie addCookie(XWikiContext context) {
      Cookie cookie = new Cookie("visitid", RandomStringUtils.randomAlphanumeric(32).toUpperCase());
      cookie.setPath("/");

     int time = (int)(expirationDate.getTime() - (new Date()).getTime())/1000;
     cookie.setMaxAge(time);

     String cookieDomain = null;
     if (cookieDomains!=null) {
        String servername = context.getRequest().getServerName();
        for (int i=0;i<cookieDomains.length;i++) {
         if (servername.indexOf(cookieDomains[i])!=-1) {
           cookieDomain = cookieDomains[i];
           break;
         }
        }
    }

    if (cookieDomain!=null) {
            cookie.setDomain(cookieDomain);
    }

    if (log.isWarnEnabled()) {
        log.warn("Setting cookie " + cookie.getValue() + " for name " + cookie.getName()
                + " with domain " + cookie.getDomain() + " and path " + cookie.getPath()
                + " and maxage " + cookie.getMaxAge());
    }

    context.getResponse().addCookie(cookie);
    return cookie;
   }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?