KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > marketing > tracking > TrackingCodeEvents


1 /*
2  * $Id: TrackingCodeEvents.java 5462 2005-08-05 18:35:48Z 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.marketing.tracking;
25
26 import java.util.ArrayList JavaDoc;
27 import java.util.LinkedList JavaDoc;
28 import java.util.List JavaDoc;
29
30 import javax.servlet.http.Cookie JavaDoc;
31 import javax.servlet.http.HttpServletRequest JavaDoc;
32 import javax.servlet.http.HttpServletResponse JavaDoc;
33 import javax.servlet.http.HttpSession JavaDoc;
34
35 import org.ofbiz.base.util.Debug;
36 import org.ofbiz.base.util.UtilDateTime;
37 import org.ofbiz.base.util.UtilMisc;
38 import org.ofbiz.base.util.UtilProperties;
39 import org.ofbiz.base.util.UtilValidate;
40 import org.ofbiz.webapp.stats.VisitHandler;
41 import org.ofbiz.webapp.website.WebSiteWorker;
42 import org.ofbiz.entity.GenericDelegator;
43 import org.ofbiz.entity.GenericEntityException;
44 import org.ofbiz.entity.GenericValue;
45 import org.ofbiz.product.category.CategoryWorker;
46
47 /**
48  * Events used for maintaining TrackingCode related information
49  *
50  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
51  * @version $Rev: 5462 $
52  * @since 2.0
53  */

54 public class TrackingCodeEvents {
55
56     public static final String JavaDoc module = TrackingCodeEvents.class.getName();
57
58     /** If TrackingCode monitoring is desired this event should be added to the list
59      * of events that run on every request. This event looks for the parameter
60      * <code>autoTrackingCode</code> or a shortened version: <code>atc</code>.
61      */

62     public static String JavaDoc checkTrackingCodeUrlParam(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
63         String JavaDoc trackingCodeId = request.getParameter("autoTrackingCode");
64         if (UtilValidate.isEmpty(trackingCodeId)) trackingCodeId = request.getParameter("atc");
65         
66         if (UtilValidate.isNotEmpty(trackingCodeId)) {
67             //tracking code is specified on the request, get the TrackingCode value and handle accordingly
68
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
69             GenericValue trackingCode = null;
70             try {
71                 trackingCode = delegator.findByPrimaryKeyCache("TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId));
72             } catch (GenericEntityException e) {
73                 Debug.logError(e, "Error looking up TrackingCode with trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId", module);
74                 return "error";
75             }
76             
77             if (trackingCode == null) {
78                 Debug.logError("TrackingCode not found for trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId.", module);
79                 //this return value will be ignored, but we'll designate this as an error anyway
80
return "error";
81             }
82
83             return processTrackingCode(trackingCode, request, response);
84         } else {
85             return "success";
86         }
87     }
88
89     /** If TrackingCode monitoring is desired this event should be added to the list
90      * of events that run on every request. This event looks for the parameter
91      * <code>ptc</code> and handles the value as a Partner Managed Tracking Code.
92      *
93      * If the specified trackingCodeId exists then it is used as is, otherwise a new one
94      * is created with the ptc value as the trackingCodeId. The values for the fields of
95      * the new TrackingCode can come from one of two places: if a <code>dtc</code> parameter
96      * is included the value will be used to lookup a TrackingCode with default values,
97      * otherwise the default trackingCodeId will be looked up in the <code>partner.trackingCodeId.default</code>
98      * in the <code>general.properties</code> file. If that is still not found just use an empty TrackingCode.
99      */

100     public static String JavaDoc checkPartnerTrackingCodeUrlParam(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
101         String JavaDoc trackingCodeId = request.getParameter("ptc");
102         
103         if (UtilValidate.isNotEmpty(trackingCodeId)) {
104             //partner managed tracking code is specified on the request
105
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
106             GenericValue trackingCode = null;
107             try {
108                 trackingCode = delegator.findByPrimaryKeyCache("TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId));
109             } catch (GenericEntityException e) {
110                 Debug.logError(e, "Error looking up TrackingCode with trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId", module);
111                 return "error";
112             }
113             
114             if (trackingCode == null) {
115                 //create new TrackingCode with default values from a "dtc" parameter or from a properties file
116

117                 String JavaDoc dtc = request.getParameter("dtc");
118                 if (UtilValidate.isEmpty(dtc)) {
119                     dtc = UtilProperties.getPropertyValue("general", "partner.trackingCodeId.default");
120                 }
121                 if (UtilValidate.isNotEmpty(dtc)) {
122                     GenericValue defaultTrackingCode = null;
123                     try {
124                         defaultTrackingCode = delegator.findByPrimaryKeyCache("TrackingCode", UtilMisc.toMap("trackingCodeId", dtc));
125                     } catch (GenericEntityException e) {
126                         Debug.logError(e, "Error looking up Default values TrackingCode with trackingCodeId [" + dtc + "], not using the dtc value for new TrackingCode defaults", module);
127                     }
128                     
129                     if (defaultTrackingCode != null) {
130                         defaultTrackingCode.set("trackingCodeId", trackingCodeId);
131                         defaultTrackingCode.set("trackingCodeTypeId", "PARTNER_MGD");
132                         //null out userLogin fields, no use tracking to customer, or is there?; set dates to current
133
defaultTrackingCode.set("createdDate", UtilDateTime.nowTimestamp());
134                         defaultTrackingCode.set("createdByUserLogin", null);
135                         defaultTrackingCode.set("lastModifiedDate", UtilDateTime.nowTimestamp());
136                         defaultTrackingCode.set("lastModifiedByUserLogin", null);
137                         
138                         trackingCode = defaultTrackingCode;
139                         try {
140                             trackingCode.create();
141                         } catch (GenericEntityException e) {
142                             Debug.logError(e, "Error creating new Partner TrackingCode with trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId", module);
143                             return "error";
144                         }
145                     }
146                 }
147                 
148                 //if trackingCode is still null then the defaultTrackingCode thing didn't work out, use empty TrackingCode
149
if (trackingCode == null) {
150                     trackingCode = delegator.makeValue("TrackingCode", null);
151                     trackingCode.set("trackingCodeId", trackingCodeId);
152                     trackingCode.set("trackingCodeTypeId", "PARTNER_MGD");
153                     //leave userLogin fields empty, no use tracking to customer, or is there?; set dates to current
154
trackingCode.set("createdDate", UtilDateTime.nowTimestamp());
155                     trackingCode.set("lastModifiedDate", UtilDateTime.nowTimestamp());
156
157                     //use nearly unlimited trackable lifetime: 10 billion seconds, 310 years
158
trackingCode.set("trackableLifetime", new Long JavaDoc(10000000000L));
159                     //use 2592000 seconds as billable lifetime: equals 1 month
160
trackingCode.set("billableLifetime", new Long JavaDoc(2592000));
161
162                     trackingCode.set("comments", "This TrackingCode has default values because no default TrackingCode could be found.");
163                     
164                     Debug.logWarning("No default TrackingCode record was found, using a TrackingCode with hard coded default values: " + trackingCode, module);
165                     
166                     try {
167                         trackingCode.create();
168                     } catch (GenericEntityException e) {
169                         Debug.logError(e, "Error creating new Partner TrackingCode with trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId", module);
170                         return "error";
171                     }
172                 }
173             }
174
175             return processTrackingCode(trackingCode, request, response);
176         } else {
177             return "success";
178         }
179     }
180
181     private static String JavaDoc processTrackingCode(GenericValue trackingCode, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
182         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
183         String JavaDoc trackingCodeId = trackingCode.getString("trackingCodeId");
184         
185         //check effective dates
186
java.sql.Timestamp JavaDoc nowStamp = UtilDateTime.nowTimestamp();
187         if (trackingCode.get("fromDate") != null && nowStamp.before(trackingCode.getTimestamp("fromDate"))) {
188             if (Debug.infoOn()) Debug.logInfo("The TrackingCode with ID [" + trackingCodeId + "] has not yet gone into effect, ignoring this trackingCodeId", module);
189             return "success";
190         }
191         if (trackingCode.get("thruDate") != null && nowStamp.after(trackingCode.getTimestamp("thruDate"))) {
192             if (Debug.infoOn()) Debug.logInfo("The TrackingCode with ID [" + trackingCodeId + "] has expired, ignoring this trackingCodeId", module);
193             return "success";
194         }
195         
196         //persist that info by associating with the current visit
197
GenericValue visit = VisitHandler.getVisit(request.getSession());
198         if (visit == null) {
199             Debug.logWarning("Could not get visit, not associating trackingCode [" + trackingCodeId + "] with visit", module);
200         } else {
201             GenericValue trackingCodeVisit = delegator.makeValue("TrackingCodeVisit",
202                     UtilMisc.toMap("trackingCodeId", trackingCodeId, "visitId", visit.get("visitId"),
203                     "fromDate", UtilDateTime.nowTimestamp(), "sourceEnumId", "TKCDSRC_URL_PARAM"));
204             try {
205                 trackingCodeVisit.create();
206             } catch (GenericEntityException e) {
207                 Debug.logError(e, "Error while saving TrackingCodeVisit", module);
208             }
209         }
210
211         
212         // write trackingCode cookies with the value set to the trackingCodeId
213
// NOTE: just write these cookies and if others exist from other tracking codes they will be overwritten, ie only keep the newest
214

215         // load the properties from the website entity
216
String JavaDoc cookieDomain = null;
217         
218         String JavaDoc webSiteId = WebSiteWorker.getWebSiteId(request);
219         if (webSiteId != null) {
220             try {
221                 GenericValue webSite = delegator.findByPrimaryKeyCache("WebSite", UtilMisc.toMap("webSiteId", webSiteId));
222                 if (webSite != null) {
223                     cookieDomain = webSite.getString("cookieDomain");
224                 }
225             } catch (GenericEntityException e) {
226                 Debug.logWarning(e, "Problems with WebSite entity; using global default cookie domain", module);
227             }
228         }
229
230         if (cookieDomain == null) {
231             cookieDomain = UtilProperties.getPropertyValue("url", "cookie.domain", "");
232         }
233
234         // if trackingCode.trackableLifetime not null and is > 0 write a trackable cookie with name in the form: TKCDT_{trackingCode.trackingCodeTypeId} and timeout will be trackingCode.trackableLifetime
235
Long JavaDoc trackableLifetime = trackingCode.getLong("trackableLifetime");
236         if (trackableLifetime != null && trackableLifetime.longValue() > 0) {
237             Cookie JavaDoc trackableCookie = new Cookie JavaDoc("TKCDT_" + trackingCode.getString("trackingCodeTypeId"), trackingCode.getString("trackingCodeId"));
238             trackableCookie.setMaxAge(trackableLifetime.intValue());
239             trackableCookie.setPath("/");
240             trackableCookie.setVersion(1);
241             if (cookieDomain.length() > 0) trackableCookie.setDomain(cookieDomain);
242             response.addCookie(trackableCookie);
243         }
244         
245         // if trackingCode.billableLifetime not null and is > 0 write a billable cookie with name in the form: TKCDB_{trackingCode.trackingCodeTypeId} and timeout will be trackingCode.billableLifetime
246
Long JavaDoc billableLifetime = trackingCode.getLong("billableLifetime");
247         if (billableLifetime != null && billableLifetime.longValue() > 0) {
248             Cookie JavaDoc billableCookie = new Cookie JavaDoc("TKCDB_" + trackingCode.getString("trackingCodeTypeId"), trackingCode.getString("trackingCodeId"));
249             billableCookie.setMaxAge(billableLifetime.intValue());
250             billableCookie.setPath("/");
251             billableCookie.setVersion(1);
252             if (cookieDomain.length() > 0) billableCookie.setDomain(cookieDomain);
253             response.addCookie(billableCookie);
254         }
255
256         // if we have overridden logo, css and/or catalogId set some session attributes
257
HttpSession JavaDoc session = request.getSession();
258         String JavaDoc overrideLogo = trackingCode.getString("overrideLogo");
259         if (overrideLogo != null)
260             session.setAttribute("overrideLogo", overrideLogo);
261         String JavaDoc overrideCss = trackingCode.getString("overrideCss");
262         if (overrideCss != null)
263             session.setAttribute("overrideCss", overrideCss);
264         String JavaDoc prodCatalogId = trackingCode.getString("prodCatalogId");
265         if (prodCatalogId != null && prodCatalogId.length() > 0) {
266             session.setAttribute("CURRENT_CATALOG_ID", prodCatalogId);
267             CategoryWorker.setTrail(request, new ArrayList JavaDoc());
268         }
269         
270         // if forward/redirect is needed, do a response.sendRedirect and return null to tell the control servlet to not do any other requests/views
271
String JavaDoc redirectUrl = trackingCode.getString("redirectUrl");
272         if (UtilValidate.isNotEmpty(redirectUrl)) {
273             try {
274                 response.sendRedirect(redirectUrl);
275             } catch (java.io.IOException JavaDoc e) {
276                 Debug.logError(e, "Could not redirect as requested in the trackingCode to: " + redirectUrl, module);
277             }
278             return null;
279         }
280                 
281         return "success";
282     }
283     
284     /** If attaching TrackingCode Cookies to the visit is desired this event should be added to the list
285      * of events that run on the first hit in a visit.
286      */

287     public static String JavaDoc checkTrackingCodeCookies(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
288         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
289         java.sql.Timestamp JavaDoc nowStamp = UtilDateTime.nowTimestamp();
290         GenericValue visit = VisitHandler.getVisit(request.getSession());
291         if (visit == null) {
292             Debug.logWarning("Could not get visit, not checking trackingCode cookies to associate with visit", module);
293         } else {
294             // loop through cookies and look for ones with a name that starts with TKCDT_ for trackable cookies
295
Cookie JavaDoc[] cookies = request.getCookies();
296
297             if (cookies != null && cookies.length > 0) {
298                 for (int i = 0; i < cookies.length; i++) {
299                     if (cookies[i].getName().startsWith("TKCDT_")) {
300                         String JavaDoc trackingCodeId = cookies[i].getValue();
301                         GenericValue trackingCode = null;
302                         try {
303                             trackingCode = delegator.findByPrimaryKeyCache("TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId));
304                         } catch (GenericEntityException e) {
305                             Debug.logError(e, "Error looking up TrackingCode with trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId", module);
306                             continue;
307                         }
308
309                         if (trackingCode == null) {
310                             Debug.logError("TrackingCode not found for trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId.", module);
311                             //this return value will be ignored, but we'll designate this as an error anyway
312
continue;
313                         }
314
315                         //check effective dates
316
if (trackingCode.get("fromDate") != null && nowStamp.before(trackingCode.getTimestamp("fromDate"))) {
317                             if (Debug.infoOn()) Debug.logInfo("The TrackingCode with ID [" + trackingCodeId + "] has not yet gone into effect, ignoring this trackingCodeId", module);
318                             continue;
319                         }
320                         if (trackingCode.get("thruDate") != null && nowStamp.after(trackingCode.getTimestamp("thruDate"))) {
321                             if (Debug.infoOn()) Debug.logInfo("The TrackingCode with ID [" + trackingCodeId + "] has expired, ignoring this trackingCodeId", module);
322                             continue;
323                         }
324                         
325                         // for each trackingCodeId found in this way attach to the visit with the TKCDSRC_COOKIE sourceEnumId
326
GenericValue trackingCodeVisit = delegator.makeValue("TrackingCodeVisit",
327                                 UtilMisc.toMap("trackingCodeId", trackingCodeId, "visitId", visit.get("visitId"),
328                                 "fromDate", nowStamp, "sourceEnumId", "TKCDSRC_COOKIE"));
329                         try {
330                             //not doing this inside a transaction, want each one possible to go in
331
trackingCodeVisit.create();
332                         } catch (GenericEntityException e) {
333                             Debug.logError(e, "Error while saving TrackingCodeVisit", module);
334                             //don't return error, want to get as many as possible: return "error";
335
}
336                     }
337                 }
338             }
339         }
340         
341         return "success";
342     }
343     
344     /** Makes a list of TrackingCodeOrder entities to be attached to the current order; called by the createOrder event; the values in the returned List will not have the orderId set */
345     public static List JavaDoc makeTrackingCodeOrders(HttpServletRequest JavaDoc request) {
346         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
347         java.sql.Timestamp JavaDoc nowStamp = UtilDateTime.nowTimestamp();
348         List JavaDoc trackingCodeOrders = new LinkedList JavaDoc();
349         
350         Cookie JavaDoc[] cookies = request.getCookies();
351         if (cookies != null && cookies.length > 0) {
352             for (int i = 0; i < cookies.length; i++) {
353                 // find any that start with TKCDB_ for billable tracking code cookies with isBillable=Y
354
// also and for each TKCDT_ cookie that doesn't have a corresponding billable code add it to the list with isBillable=N
355

356                 String JavaDoc isBillable = null;
357                 String JavaDoc cookieName = cookies[i].getName();
358                 if (cookieName.startsWith("TKCDB_")) {
359                     isBillable = "Y";
360                 } else if (cookieName.startsWith("TKCDT_")) {
361                     isBillable = "N";
362                 }
363                 
364                 if (isBillable != null) {
365                     String JavaDoc trackingCodeId = cookies[i].getValue();
366                     GenericValue trackingCode = null;
367                     try {
368                         trackingCode = delegator.findByPrimaryKeyCache("TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId));
369                     } catch (GenericEntityException e) {
370                         Debug.logError(e, "Error looking up TrackingCode with trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId", module);
371                         continue;
372                     }
373
374                     if (trackingCode == null) {
375                         Debug.logError("TrackingCode not found for trackingCodeId [" + trackingCodeId + "], ignoring this trackingCodeId.", module);
376                         //this return value will be ignored, but we'll designate this as an error anyway
377
continue;
378                     }
379
380                     //check effective dates
381
if (trackingCode.get("fromDate") != null && nowStamp.before(trackingCode.getTimestamp("fromDate"))) {
382                         if (Debug.infoOn()) Debug.logInfo("The TrackingCode with ID [" + trackingCodeId + "] has not yet gone into effect, ignoring this trackingCodeId", module);
383                         continue;
384                     }
385                     if (trackingCode.get("thruDate") != null && nowStamp.after(trackingCode.getTimestamp("thruDate"))) {
386                         if (Debug.infoOn()) Debug.logInfo("The TrackingCode with ID [" + trackingCodeId + "] has expired, ignoring this trackingCodeId", module);
387                         continue;
388                     }
389                     
390                     // a quick sanity check here on the trackingCodeTypeId, will just display a warning if this happens but not do anythin about it for now
391

392                     // note: using TKCDB_ only for length because both TKCDB_ and TKCDT_ are the same length
393
String JavaDoc cookieTrackingCodeTypeId = cookieName.substring("TKCDB_".length());
394                     if (cookieTrackingCodeTypeId == null || cookieTrackingCodeTypeId.length() == 0) {
395                         Debug.logWarning("The trackingCodeTypeId as part of the cookie name was null or empty", module);
396                     } else if (!cookieTrackingCodeTypeId.equals(trackingCode.getString("trackingCodeTypeId"))) {
397                         Debug.logWarning("The trackingCodeTypeId [" + cookieTrackingCodeTypeId + "] as part of the cookie name was equal to the current trackingCodeTypeId [" + trackingCode.getString("trackingCodeTypeId") + "] associated with the trackingCodeId [" + trackingCodeId + "]", module);
398                     }
399                     
400                     // this will have everything except the orderId set, that will be set by the createOrder service
401
GenericValue trackingCodeOrder = delegator.makeValue("TrackingCodeOrder",
402                             UtilMisc.toMap("trackingCodeTypeId", trackingCode.get("trackingCodeTypeId"),
403                             "trackingCodeId", trackingCodeId, "isBillable", isBillable));
404                     
405                     trackingCodeOrders.add(trackingCodeOrder);
406                 }
407             }
408         }
409
410         return trackingCodeOrders;
411     }
412 }
413
Popular Tags