KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > accounting > thirdparty > worldpay > SelectRespServlet


1 /*
2  * $Id: SelectRespServlet.java 6642 2006-02-01 02:29:51Z sichen $
3  *
4  * Copyright (c) 2003 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  */

25 package org.ofbiz.accounting.thirdparty.worldpay;
26
27 import java.io.IOException JavaDoc;
28 import java.util.Enumeration JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Locale JavaDoc;
32 import java.util.Map JavaDoc;
33
34 import javax.servlet.ServletContext JavaDoc;
35 import javax.servlet.ServletException JavaDoc;
36 import javax.servlet.ServletOutputStream JavaDoc;
37 import javax.servlet.ServletRequest JavaDoc;
38 import javax.servlet.http.HttpSession JavaDoc;
39
40 import org.ofbiz.base.util.Debug;
41 import org.ofbiz.base.util.GeneralException;
42 import org.ofbiz.base.util.StringUtil;
43 import org.ofbiz.base.util.UtilMisc;
44 import org.ofbiz.webapp.view.JPublishWrapper;
45 import org.ofbiz.entity.GenericDelegator;
46 import org.ofbiz.entity.GenericEntityException;
47 import org.ofbiz.entity.GenericValue;
48 import org.ofbiz.entity.transaction.GenericTransactionException;
49 import org.ofbiz.entity.transaction.TransactionUtil;
50 import org.ofbiz.order.order.OrderChangeHelper;
51 import org.ofbiz.service.ModelService;
52 import org.ofbiz.service.DispatchContext;
53 import org.ofbiz.service.GenericServiceException;
54 import org.ofbiz.service.LocalDispatcher;
55 import org.ofbiz.service.ServiceDispatcher;
56
57 import com.worldpay.select.SelectDefs;
58 import com.worldpay.select.merchant.SelectServlet;
59 import com.worldpay.select.merchant.SelectServletRequest;
60 import com.worldpay.select.merchant.SelectServletResponse;
61
62 /**
63  * WorldPay Select Pro Response Servlet
64  *
65  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
66  * @version $Rev: 6642 $
67  * @since 2.0
68  */

69 public class SelectRespServlet extends SelectServlet implements SelectDefs {
70     
71     public static final String JavaDoc module = SelectRespServlet.class.getName();
72     protected JPublishWrapper jp = null;
73
74     protected void doRequest(SelectServletRequest request, SelectServletResponse response) throws ServletException JavaDoc, IOException JavaDoc {
75         Debug.logInfo("Response received from worldpay..", module);
76                 
77         String JavaDoc localLocaleStr = request.getParameter("M_localLocale");
78         String JavaDoc webSiteId = request.getParameter("M_webSiteId");
79         String JavaDoc delegatorName = request.getParameter("M_delegatorName");
80         String JavaDoc dispatchName = request.getParameter("M_dispatchName");
81         String JavaDoc userLoginId = request.getParameter("M_userLoginId");
82         String JavaDoc confirmTemplate = request.getParameter("M_confirmTemplate");
83         
84         // get the ServletContext
85
ServletContext JavaDoc context = (ServletContext JavaDoc) request.getAttribute("servletContext");
86         if (this.jp == null) {
87             this.jp = (JPublishWrapper) context.getAttribute("jpublishWrapper");
88             if (this.jp == null) {
89                 this.jp = new JPublishWrapper(context);
90             }
91         }
92         
93         // get the delegator
94
GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorName);
95         
96         // get the dispatcher
97
ServiceDispatcher serviceDisp = ServiceDispatcher.getInstance(dispatchName, delegator);
98         DispatchContext dctx = serviceDisp.getLocalContext(dispatchName);
99         LocalDispatcher dispatcher = dctx.getDispatcher();
100         
101         // get the userLogin
102
GenericValue userLogin = null;
103         try {
104             userLogin = delegator.findByPrimaryKey("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
105         } catch (GenericEntityException e) {
106             Debug.logError(e, "Cannot get admin UserLogin entity", module);
107             callError(request);
108         }
109         
110         // get the client locale
111
List JavaDoc localeSplit = StringUtil.split(localLocaleStr, "_");
112         Locale JavaDoc localLocale = new Locale JavaDoc((String JavaDoc) localeSplit.get(0), (String JavaDoc) localeSplit.get(1));
113                 
114         // get the properties file
115
String JavaDoc configString = null;
116         try {
117             GenericValue webSitePayment = delegator.findByPrimaryKey("WebSitePaymentSetting", UtilMisc.toMap("webSiteId", webSiteId, "paymentMethodTypeId", "EXT_WORLDPAY"));
118             if (webSitePayment != null)
119                 configString = webSitePayment.getString("paymentConfiguration");
120         } catch (GenericEntityException e) {
121             Debug.logWarning(e, "Cannot find webSitePayment Settings", module);
122         }
123         if (configString == null)
124         configString = "payment.properties";
125         Debug.logInfo("Got the payment configuration", module);
126         
127         String JavaDoc orderId = request.getParameter(SelectDefs.SEL_cartId);
128         String JavaDoc authAmount = request.getParameter(SelectDefs.SEL_authAmount);
129         String JavaDoc transStatus = request.getParameter(SelectDefs.SEL_transStatus);
130         
131         // get the order header
132
GenericValue orderHeader = null;
133         try {
134             orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
135         } catch (GenericEntityException e) {
136             Debug.logError(e, "Cannot get the order header for the returned orderId", module);
137             callError(request);
138         }
139         
140         // the order total MUST match the auth amount or we do not process
141
Double JavaDoc wpTotal = new Double JavaDoc(authAmount);
142         Double JavaDoc orderTotal = orderHeader != null ? orderHeader.getDouble("grandTotal") : null;
143         if (orderTotal != null && wpTotal != null) {
144             if (orderTotal.doubleValue() != wpTotal.doubleValue()) {
145                 Debug.logError("AuthAmount (" + wpTotal + ") does not match OrderTotal (" + orderTotal + ")", module);
146                 callError(request);
147             }
148         }
149         
150         // store some stuff for calling existing events
151
HttpSession JavaDoc session = request.getSession(true);
152         session.setAttribute("userLogin", userLogin);
153         
154         request.setAttribute("delegator", delegator);
155         request.setAttribute("dispatcher", dispatcher);
156         request.setAttribute("orderId", orderId);
157         request.setAttribute("notifyEmail", request.getParameter("M_notifyEmail"));
158         request.setAttribute("confirmEmail", request.getParameter("M_confirmEmail"));
159         request.setAttribute("_CONTROL_PATH_", request.getParameter("M_controlPath"));
160                 
161         // attempt to start a transaction
162
boolean beganTransaction = false;
163         try {
164             beganTransaction = TransactionUtil.begin();
165         } catch (GenericTransactionException gte) {
166             Debug.logError(gte, "Unable to begin transaction", module);
167         }
168         
169         boolean okay = false;
170         if (transStatus.equalsIgnoreCase("Y")) {
171             // order was approved
172
Debug.logInfo("Order #" + orderId + " approved", module);
173             okay = OrderChangeHelper.approveOrder(dispatcher, userLogin, orderId);
174         } else {
175             // order was cancelled
176
Debug.logInfo("Order #" + orderId + " cancelled", module);
177             okay = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
178         }
179         
180         if (okay) {
181             // set the payment preference
182
okay = setPaymentPreferences(delegator, userLogin, orderId, request);
183         }
184         
185         if (okay) {
186             try {
187                 TransactionUtil.commit(beganTransaction);
188             } catch (GenericTransactionException gte) {
189                 Debug.logError(gte, "Unable to commit transaction", module);
190             }
191         } else {
192             try {
193                 TransactionUtil.rollback(beganTransaction, "Failure in Worldpay callback/response processing.", null);
194             } catch (GenericTransactionException gte) {
195                 Debug.logError(gte, "Unable to rollback transaction", module);
196             }
197         }
198         
199         // attempt to release the offline hold on the order (workflow)
200
OrderChangeHelper.releaseInitialOrderHold(dispatcher, orderId);
201                         
202         // call the email confirm service
203
Map JavaDoc emailContext = UtilMisc.toMap("orderId", orderId);
204         try {
205             Map JavaDoc emailResult = dispatcher.runSync("sendOrderConfirmation", emailContext);
206         } catch (GenericServiceException e) {
207             Debug.logError(e, "Problems sending email confirmation", module);
208         }
209                                                               
210         // set up the output stream for the response
211
response.setContentType("text/html");
212         ServletOutputStream JavaDoc out = response.getOutputStream();
213         String JavaDoc content = "Error getting confirm content";
214         if (confirmTemplate != null) {
215             // render the thank-you / confirm page
216
try {
217                 content = jp.render(confirmTemplate, request, response);
218             } catch (GeneralException e) {
219                 Debug.logError(e, "Trouble rendering confirm page", module);
220             }
221         }
222         out.println(content);
223         out.flush();
224     }
225                
226     private boolean setPaymentPreferences(GenericDelegator delegator, GenericValue userLogin, String JavaDoc orderId, ServletRequest JavaDoc request) {
227         List JavaDoc paymentPrefs = null;
228         boolean okay = true;
229         try {
230             Map JavaDoc paymentFields = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_NOT_RECEIVED");
231             paymentPrefs = delegator.findByAnd("OrderPaymentPreference", paymentFields);
232         } catch (GenericEntityException e) {
233             Debug.logError(e, "Cannot get payment preferences for order #" + orderId, module);
234         }
235         if (paymentPrefs != null && paymentPrefs.size() > 0) {
236             Iterator JavaDoc i = paymentPrefs.iterator();
237             while (okay && i.hasNext()) {
238                 GenericValue pref = (GenericValue) i.next();
239                 okay = setPaymentPreference(pref, userLogin, request);
240             }
241         }
242         return okay;
243     }
244         
245     private boolean setPaymentPreference(GenericValue paymentPreference, GenericValue userLogin, ServletRequest JavaDoc request) {
246         String JavaDoc transId = request.getParameter(SelectDefs.SEL_transId);
247         String JavaDoc transTime = request.getParameter(SelectDefs.SEL_transTime);
248         String JavaDoc transStatus = request.getParameter(SelectDefs.SEL_transStatus);
249         String JavaDoc avsCode = request.getParameter("AVS"); // why is this not in SelectDefs??
250
String JavaDoc authCode = request.getParameter(SelectDefs.SEL_authCode);
251         String JavaDoc authAmount = request.getParameter(SelectDefs.SEL_authAmount);
252         String JavaDoc rawAuthMessage = request.getParameter(SelectDefs.SEL_rawAuthMessage);
253         
254         // Need these for create payment service
255
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
256         
257         if (transStatus.equalsIgnoreCase("Y")) {
258             paymentPreference.set("authCode", authCode);
259             paymentPreference.set("statusId", "PAYMENT_RECEIVED");
260         } else {
261             paymentPreference.set("statusId", "PAYMENT_CANCELLED");
262         }
263         Long JavaDoc transTimeLong = new Long JavaDoc(transTime);
264         java.sql.Timestamp JavaDoc authDate = new java.sql.Timestamp JavaDoc(transTimeLong.longValue());
265         
266         paymentPreference.set("avsCode", avsCode);
267         paymentPreference.set("authRefNum", transId);
268         paymentPreference.set("authDate", authDate);
269         paymentPreference.set("authFlag", transStatus);
270         paymentPreference.set("authMessage", rawAuthMessage);
271         paymentPreference.set("maxAmount", new Double JavaDoc(authAmount));
272         
273         // create a payment record too -- this method does not store the object so we must here
274
Map JavaDoc results = null;
275         try {
276             results = dispatcher.runSync("createPaymentFromPreference", UtilMisc.toMap("userLogin", userLogin,
277                     "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "comments", "Payment received via WorldPay"));
278         } catch (GenericServiceException e) {
279             Debug.logError(e, "Failed to execute service createPaymentFromPreference", module);
280             request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
281             return false;
282         }
283
284         if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR))) {
285             Debug.logError((String JavaDoc) results.get(ModelService.ERROR_MESSAGE), module);
286             request.setAttribute("_ERROR_MESSAGE_", (String JavaDoc) results.get(ModelService.ERROR_MESSAGE));
287             return false;
288         }
289         
290         try {
291             paymentPreference.store();
292             paymentPreference.getDelegator().create(paymentPreference);
293         } catch (GenericEntityException e) {
294             Debug.logError(e, "Cannot set payment preference/payment info", module);
295             return false;
296         }
297         return true;
298     }
299     
300     private void callError(ServletRequest JavaDoc request) throws ServletException JavaDoc {
301         Enumeration JavaDoc e = request.getParameterNames();
302         Debug.logError("###### SelectRespServlet Error:", module);
303         while (e.hasMoreElements()) {
304             String JavaDoc name = (String JavaDoc) e.nextElement();
305             String JavaDoc value = request.getParameter(name);
306             Debug.logError("### Parameter: " + name + " => " + value, module);
307         }
308         Debug.logError("###### The order was not processed!", module);
309         throw new ServletException JavaDoc("Order Error");
310     }
311 }
312
Popular Tags