KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webapp > stats > VisitHandler


1 /*
2  * $Id: VisitHandler.java 6595 2006-01-27 00:39:35Z jonesde $
3  *
4  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.webapp.stats;
25
26 import java.net.InetAddress JavaDoc;
27 import java.sql.Timestamp JavaDoc;
28
29 import javax.servlet.http.Cookie JavaDoc;
30 import javax.servlet.http.HttpServletRequest JavaDoc;
31 import javax.servlet.http.HttpServletResponse JavaDoc;
32 import javax.servlet.http.HttpSession JavaDoc;
33
34 import org.ofbiz.base.util.Debug;
35 import org.ofbiz.base.util.UtilHttp;
36 import org.ofbiz.base.util.UtilMisc;
37 import org.ofbiz.base.util.UtilProperties;
38 import org.ofbiz.base.util.UtilValidate;
39 import org.ofbiz.entity.GenericDelegator;
40 import org.ofbiz.entity.GenericEntityException;
41 import org.ofbiz.entity.GenericValue;
42
43 /**
44  * Handles saving and maintaining visit information
45  *
46  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
47  * @version $Rev: 6595 $
48  * @since 2.0
49  */

50 public class VisitHandler {
51     // Debug module name
52
public static final String JavaDoc module = VisitHandler.class.getName();
53     
54     public static final String JavaDoc visitorCookieName = "OFBiz.Visitor";
55
56     // this is not an event because it is required to run; as an event it could be disabled.
57
public static void setInitialVisit(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
58         HttpSession JavaDoc session = request.getSession();
59
60         // init the visitor
61
getVisitor(request, response);
62         
63         String JavaDoc webappName = UtilHttp.getApplicationName(request);
64         StringBuffer JavaDoc fullRequestUrl = UtilHttp.getFullRequestUrl(request);
65         String JavaDoc initialLocale = request.getLocale() != null ? request.getLocale().toString() : "";
66         String JavaDoc initialRequest = fullRequestUrl.toString();
67         String JavaDoc initialReferrer = request.getHeader("Referer") != null ? request.getHeader("Referer") : "";
68         String JavaDoc initialUserAgent = request.getHeader("User-Agent") != null ? request.getHeader("User-Agent") : "";
69
70         session.setAttribute("_CLIENT_LOCALE_", request.getLocale());
71         session.setAttribute("_CLIENT_REQUEST_", initialRequest);
72         session.setAttribute("_CLIENT_USER_AGENT_", initialUserAgent);
73         session.setAttribute("_CLIENT_REFERER_", initialUserAgent);
74         VisitHandler.setInitials(request, session, initialLocale, initialRequest, initialReferrer, initialUserAgent, webappName);
75     }
76
77     public static void setInitials(HttpServletRequest JavaDoc request, HttpSession JavaDoc session, String JavaDoc initialLocale, String JavaDoc initialRequest, String JavaDoc initialReferrer, String JavaDoc initialUserAgent, String JavaDoc webappName) {
78         GenericValue visit = getVisit(session);
79
80         if (visit != null) {
81             visit.set("initialLocale", initialLocale);
82             if (initialRequest != null) visit.set("initialRequest", initialRequest.length() > 250 ? initialRequest.substring(0, 250) : initialRequest);
83             if (initialReferrer != null) visit.set("initialReferrer", initialReferrer.length() > 250 ? initialReferrer.substring(0, 250) : initialReferrer);
84             if (initialUserAgent != null) visit.set("initialUserAgent", initialUserAgent.length() > 250 ? initialUserAgent.substring(0, 250) : initialUserAgent);
85             visit.set("webappName", webappName);
86             if (UtilProperties.propertyValueEquals("serverstats", "stats.proxy.enabled", "true")){
87                 visit.set("clientIpAddress", request.getHeader("X-Forwarded-For"));
88             } else {
89                 visit.set("clientIpAddress", request.getRemoteAddr());
90             }
91             visit.set("clientHostName", request.getRemoteHost());
92             visit.set("clientUser", request.getRemoteUser());
93
94             try {
95                 visit.store();
96             } catch (GenericEntityException e) {
97                 Debug.logError(e, "Could not update visit:", module);
98             }
99         }
100     }
101
102     public static void setUserLogin(HttpSession JavaDoc session, GenericValue userLogin, boolean userCreated) {
103         if (userLogin == null) return;
104
105         GenericValue visitor = (GenericValue) session.getAttribute("visitor");
106         if (visitor != null) {
107             visitor.set("userLoginId", userLogin.get("userLoginId"));
108             visitor.set("partyId", userLogin.get("partyId"));
109             try {
110                 visitor.store();
111             } catch (GenericEntityException e) {
112                 Debug.logError(e, "Could not update visitor: ", module);
113             }
114         }
115         
116         GenericValue visit = getVisit(session);
117         if (visit != null) {
118             visit.set("userLoginId", userLogin.get("userLoginId"));
119             visit.set("partyId", userLogin.get("partyId"));
120             visit.set("userCreated", new Boolean JavaDoc(userCreated));
121             
122             // make sure the visitorId is still in place
123
if (visitor != null) {
124                 visit.set("visitorId", visitor.get("visitorId"));
125             }
126             
127             try {
128                 visit.store();
129             } catch (GenericEntityException e) {
130                 Debug.logError(e, "Could not update visit: ", module);
131             }
132         }
133     }
134
135     public static String JavaDoc getVisitId(HttpSession JavaDoc session) {
136         GenericValue visit = getVisit(session);
137
138         if (visit != null) {
139             return visit.getString("visitId");
140         } else {
141             return null;
142         }
143     }
144
145     /** Get the visit from the session, or create if missing */
146     public static GenericValue getVisit(HttpSession JavaDoc session) {
147         // this defaults to true: ie if anything but "false" it will be true
148
if (!UtilProperties.propertyValueEqualsIgnoreCase("serverstats", "stats.persist.visit", "false")) {
149             GenericValue visit = (GenericValue) session.getAttribute("visit");
150
151             if (visit == null) {
152                 GenericDelegator delegator = null;
153                 
154                 // first try the session attribute delegatorName
155
String JavaDoc delegatorName = (String JavaDoc) session.getAttribute("delegatorName");
156                 if (UtilValidate.isNotEmpty(delegatorName)) {
157                     delegator = GenericDelegator.getGenericDelegator(delegatorName);
158                 }
159                 
160                 // then try the ServletContext attribute delegator, should always be there...
161
if (delegator == null) {
162                     delegator = (GenericDelegator) session.getServletContext().getAttribute("delegator");
163                 }
164                 
165                 if (delegator == null) {
166                     Debug.logError("Could not find delegator with delegatorName [" + delegatorName + "] in session, or a delegator attribute in the ServletContext, not creating Visit entity", module);
167                 } else {
168                     visit = delegator.makeValue("Visit", null);
169                     visit.set("visitId", delegator.getNextSeqId("Visit"));
170                     visit.set("sessionId", session.getId());
171                     visit.set("fromDate", new Timestamp JavaDoc(session.getCreationTime()));
172                     
173                     // get the visitorId
174
GenericValue visitor = (GenericValue) session.getAttribute("visitor");
175                     if (visitor != null) {
176                         visit.set("visitorId", visitor.get("visitorId"));
177                     }
178
179                     // get localhost ip address and hostname to store
180
try {
181                         InetAddress JavaDoc address = InetAddress.getLocalHost();
182
183                         if (address != null) {
184                             visit.set("serverIpAddress", address.getHostAddress());
185                             visit.set("serverHostName", address.getHostName());
186                         } else {
187                             Debug.logError("Unable to get localhost internet address, was null", module);
188                         }
189                     } catch (java.net.UnknownHostException JavaDoc e) {
190                         Debug.logError("Unable to get localhost internet address: " + e.toString(), module);
191                     }
192                     try {
193                         visit.create();
194                         session.setAttribute("visit", visit);
195                     } catch (GenericEntityException e) {
196                         Debug.logError(e, "Could not create new visit:", module);
197                         visit = null;
198                     }
199                 }
200             }
201             if (visit == null) {
202                 Debug.logWarning("Could not find or create the visit...", module);
203             }
204             return visit;
205         } else {
206             return null;
207         }
208     }
209
210     public static GenericValue getVisitor(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
211         HttpSession JavaDoc session = request.getSession();
212         GenericValue visitor = (GenericValue) session.getAttribute("visitor");
213
214         if (visitor == null) {
215             GenericDelegator delegator = null;
216             String JavaDoc delegatorName = (String JavaDoc) session.getAttribute("delegatorName");
217
218             if (UtilValidate.isNotEmpty(delegatorName)) {
219                 delegator = GenericDelegator.getGenericDelegator(delegatorName);
220             }
221             if (delegator == null) {
222                 Debug.logError("Could not find delegator with delegatorName [" + delegatorName + "] in session, not creating/getting Visitor entity", module);
223             } else {
224                 // first try to get the current ID from the visitor cookie
225
String JavaDoc visitorId = null;
226                 Cookie JavaDoc[] cookies = request.getCookies();
227                 if (Debug.verboseOn()) Debug.logVerbose("Cookies:" + cookies, module);
228                 if (cookies != null) {
229                     for (int i = 0; i < cookies.length; i++) {
230                         if (cookies[i].getName().equals(visitorCookieName)) {
231                             visitorId = cookies[i].getValue();
232                             break;
233                         }
234                     }
235                 }
236                 
237                 if (visitorId == null) {
238                     // no visitor cookie? create visitor and send back cookie too
239
visitorId = delegator.getNextSeqId("Visitor");
240
241                     visitor = delegator.makeValue("Visitor", null);
242                     visitor.set("visitorId", visitorId);
243                     try {
244                         visitor.create();
245                     } catch (GenericEntityException e) {
246                         Debug.logError(e, "Could not create new visitor:", module);
247                         visitor = null;
248                     }
249                 } else {
250                     try {
251                         visitor = delegator.findByPrimaryKey("Visitor", UtilMisc.toMap("visitorId", visitorId));
252                     } catch (GenericEntityException e) {
253                         Debug.logError(e, "Could not find visitor with ID from cookie: " + visitorId, module);
254                         visitor = null;
255                     }
256                 }
257             }
258             
259             if (visitor != null) {
260                 // we got one, and it's a new one since it was null before
261
session.setAttribute("visitor", visitor);
262
263                 // create the cookie and send it back, this may be done over and over, in effect frequently refreshing the cookie
264
Cookie JavaDoc visitorCookie = new Cookie JavaDoc(visitorCookieName, visitor.getString("visitorId"));
265                 visitorCookie.setMaxAge(60 * 60 * 24 * 365);
266                 visitorCookie.setPath("/");
267                 response.addCookie(visitorCookie);
268             }
269         }
270         if (visitor == null) {
271             Debug.logWarning("Could not find or create the visitor...", module);
272         }
273         return visitor;
274     }
275 }
276
Popular Tags