PageRenderTime 56ms CodeModel.GetById 37ms app.highlight 16ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/paypal/controller/UserServlet.java

https://gitlab.com/CORP-RESELLER/rest-api-sample-app-java
Java | 412 lines | 285 code | 58 blank | 69 comment | 53 complexity | 44203dfc889e855f996148c88da0140e MD5 | raw file
  1package com.paypal.controller;
  2
  3import java.io.File;
  4import java.io.IOException;
  5import java.io.InputStream;
  6import java.sql.SQLException;
  7import java.util.List;
  8
  9import javax.net.ssl.HostnameVerifier;
 10import javax.net.ssl.HttpsURLConnection;
 11import javax.net.ssl.SSLSession;
 12import javax.servlet.ServletException;
 13import javax.servlet.http.HttpServlet;
 14import javax.servlet.http.HttpServletRequest;
 15import javax.servlet.http.HttpServletResponse;
 16import javax.servlet.http.HttpSession;
 17
 18import com.paypal.api.payments.CreditCard;
 19import com.paypal.core.ConfigManager;
 20import com.paypal.core.LoggingManager;
 21import com.paypal.core.rest.PayPalRESTException;
 22import com.paypal.core.rest.PayPalResource;
 23import com.paypal.dao.DBConnection;
 24import com.paypal.dao.Dao;
 25import com.paypal.model.CreditCardDetail;
 26import com.paypal.model.ErrorMessage;
 27import com.paypal.model.User;
 28import com.paypal.model.UserPaymentDetail;
 29import com.paypal.util.AppConstants;
 30import com.paypal.util.AppHelper;
 31import com.paypal.util.WebHelper;
 32
 33/**
 34 * <code>UserServlet</code> handles user management. It keeps track of sessions,
 35 * sign-ups, log-in, log-out order descriptions and profile updates
 36 * 
 37 * @author tkanta
 38 * 
 39 */
 40public class UserServlet extends HttpServlet {
 41
 42	private static final long serialVersionUID = 1231435434634644452L;
 43
 44	/**
 45	 * Initialize SDK configuration file and database connection
 46	 */
 47	@Override
 48	public void init() throws ServletException {
 49
 50		// initialize sdk configuration
 51		InputStream is = PaymentServlet.class
 52				.getResourceAsStream("/sdk_config.properties");
 53		try {
 54			PayPalResource.initConfig(is);
 55		} catch (PayPalRESTException pex) {
 56			LoggingManager.debug(PaymentServlet.class, pex.getMessage());
 57			throw new ServletException(pex);
 58		}
 59
 60		// Initialize the database drivers
 61		DBConnection.getConnection();
 62
 63	}
 64
 65	protected void doGet(HttpServletRequest request,
 66			HttpServletResponse response) throws ServletException, IOException {
 67
 68		// check if session is valid
 69		if (!WebHelper.checkSessionValidity(request)) {
 70			WebHelper.forward(request, response, AppConstants.SHOW_HOME);
 71		} else {
 72			if (request.getRequestURI().contains(AppConstants.HOME)) {
 73
 74				// ------ Show home page ----------
 75				WebHelper.forward(request, response, AppConstants.SHOW_HOME);
 76			} else if (request.getRequestURI().contains(AppConstants.SIGNUP)) {
 77
 78				// ------ Show signup page ----------
 79				WebHelper.forward(request, response, AppConstants.SHOW_SIGNUP);
 80			} else if (request.getRequestURI().contains(AppConstants.SIGNIN)) {
 81
 82				// ------ Show signin page ----------
 83				WebHelper.forward(request, response, AppConstants.SHOW_SIGNIN);
 84			} else if (request.getRequestURI().contains(AppConstants.PROFILE)) {
 85
 86				// ------ Show profile page ----------
 87				handleDisplayProfilePage(request, response);
 88			} else if (request.getRequestURI().contains(
 89					AppConstants.SHOW_ORDERS)) {
 90
 91				// ------ Show order page ----------
 92				handleDisplayOrderPage(request, response);
 93			} else if (request.getRequestURI().contains(AppConstants.SIGNOUT)) {
 94
 95				// ------ Handle signout ----------
 96				handleSignout(request, response);
 97			} else {
 98				throw new ServletException("Unknown resource requested");
 99			}
100
101		}
102	}
103
104	protected void doPost(HttpServletRequest request,
105			HttpServletResponse response) throws ServletException, IOException {
106		// check if session is valid
107		if (!WebHelper.checkSessionValidity(request)) {
108			WebHelper.redirect(request, response, AppConstants.SHOW_SIGNIN);
109		} else {
110			if (request.getRequestURI().contains(AppConstants.PLACE_ORDER)) {
111
112				// -------- User order ---------
113				handleOrder(request, response);
114			} else if (request.getRequestURI().contains(AppConstants.SIGNUP)) {
115
116				// -------- User signup ---------
117				handleSignup(request, response);
118			} else if (request.getRequestURI().contains(AppConstants.SIGNIN)) {
119
120				// -------- User signin ---------
121				handleSignin(request, response);
122			} else if (request.getRequestURI().contains(AppConstants.PROFILE)) {
123
124				// -------- User profile ---------
125				handleUpdateProfile(request, response);
126			} else {
127				throw new ServletException("Unknown resource requested");
128			}
129
130		}
131	}
132
133	/*
134	 * Handle user Sign out
135	 */
136	private void handleSignout(HttpServletRequest request,
137			HttpServletResponse response) throws ServletException, IOException {
138		HttpSession session = request.getSession(false);
139		session.invalidate();
140
141		// forward user to home
142		WebHelper.forward(request, response, AppConstants.SHOW_HOME);
143	}
144
145	/*
146	 * display order page
147	 */
148	private void handleDisplayOrderPage(HttpServletRequest request,
149			HttpServletResponse response) throws ServletException, IOException {
150
151		// Get Logged in User detail
152		HttpSession session = request.getSession(false);
153		String email = (String) session.getAttribute("user");
154		User user = null;
155		try {
156			user = Dao.getUser(email);
157		} catch (SQLException sqlex) {
158			throw new ServletException(sqlex);
159		}
160
161		List<UserPaymentDetail> paymentList = null;
162		try {
163
164			// Get User payments list
165			paymentList = Dao.getOrdersByUserId(user.getId());
166
167		} catch (SQLException sqlex) {
168			throw new ServletException(sqlex);
169		}
170		request.setAttribute("paymentList", paymentList);
171		WebHelper.forward(request, response, AppConstants.SHOW_ORDER);
172	}
173
174	/*
175	 * display profile page
176	 */
177	private void handleDisplayProfilePage(HttpServletRequest request,
178			HttpServletResponse response) throws ServletException, IOException {
179		HttpSession session = request.getSession(false);
180		String email = (String) session.getAttribute("user");
181		User user = null;
182		try {
183			user = Dao.getUser(email);
184		} catch (SQLException sqlex) {
185			throw new ServletException(sqlex);
186		}
187
188		// Get Credit Card detail
189		CreditCardDetail cardDetail = getCreditCardDetail(request, response,
190				user);
191		request.setAttribute("cardDetail", cardDetail);
192		WebHelper.forward(request, response, AppConstants.SHOW_PROFILE);
193	}
194
195	/*
196	 * Get Credit Card detail
197	 */
198	private CreditCardDetail getCreditCardDetail(HttpServletRequest request,
199			HttpServletResponse response, User user) throws ServletException,
200			IOException {
201		CreditCardDetail cardDetail = null;
202		try {
203			cardDetail = AppHelper.getCreditCardDetail(user.getCreditCardId());
204		} catch (PayPalRESTException pex) {
205			if (pex.getMessage().contains(AppConstants.VALIDATION_ERROR)) {
206				WebHelper.formErrorMessage(request, pex);
207				WebHelper.forward(request, response, AppConstants.SHOW_PROFILE);
208			} else {
209				LoggingManager.debug(PaymentServlet.class, pex.getMessage());
210				throw new ServletException(pex);
211			}
212		}
213		return cardDetail;
214	}
215
216	/*
217	 * Handle display of user payment options [ CreditCard , PayPal]
218	 */
219	private void handleOrder(HttpServletRequest request,
220			HttpServletResponse response) throws ServletException, IOException {
221		HttpSession session = request.getSession(false);
222
223		if (session != null && session.getAttribute("user") != null) {
224			String orderString = request.getQueryString();
225			String[] orderArray = orderString.split("&");
226			String orderAmount = orderArray[0].split("=")[1];
227			String orderDesc = orderArray[1].split("=")[1];
228
229			request.setAttribute("orderAmount", orderAmount);
230			request.setAttribute("orderDesc", orderDesc);
231
232			WebHelper.forward(request, response, AppConstants.SHOW_PLACE_ORDER);
233
234		} else {
235			response.sendRedirect(WebHelper.getContextPath(request) + "/signin");
236			return;
237		}
238	}
239
240	/*
241	 * Handle user sign up
242	 */
243	private void handleSignup(HttpServletRequest request,
244			HttpServletResponse response) throws ServletException, IOException {
245		String email = request.getParameter("user_email");
246		String password = request.getParameter("user_password");
247		User user = null;
248		CreditCard createdCreditCard = null;
249
250		// Retrieve User
251		try {
252			user = Dao.getUser(email);
253		} catch (SQLException sqlex) {
254			throw new ServletException(sqlex);
255		}
256
257		// Check for User existence
258		if (user != null) {
259			ErrorMessage errorMsg = new ErrorMessage();
260			errorMsg.add(AppConstants.USER_EXIST);
261			request.setAttribute("error", errorMsg);
262			WebHelper.forward(request, response, AppConstants.SHOW_SIGNUP);
263			return;
264		}
265
266		// create credit card
267		try {
268			createdCreditCard = AppHelper.createCreditCard(request);
269		} catch (PayPalRESTException pex) {
270			if (pex.getMessage().contains(AppConstants.VALIDATION_ERROR)) {
271				WebHelper.formErrorMessage(request, pex);
272				WebHelper.forward(request, response, AppConstants.SHOW_SIGNUP);
273				return;
274			} else {
275				LoggingManager.debug(PaymentServlet.class, pex.getMessage());
276				throw new ServletException(pex);
277			}
278
279		}
280
281		// Insert User
282		try {
283			Dao.insertUser(email, password, createdCreditCard.getId());
284		} catch (SQLException sqlex) {
285			throw new ServletException(sqlex);
286		}
287		HttpSession session = request.getSession();
288		session.setAttribute("isSessionActive", true);
289		session.setAttribute("user", email);
290
291		// forward User to home
292		WebHelper.forward(request, response, AppConstants.SHOW_HOME);
293	}
294
295	/*
296	 * Handle user sign in
297	 */
298	private void handleSignin(HttpServletRequest request,
299			HttpServletResponse response) throws ServletException, IOException {
300
301		// validate User
302		String email = request.getParameter("user_email");
303		String password = request.getParameter("user_password");
304		User user = null;
305		try {
306			user = Dao.getUser(email);
307			if (user == null
308					|| ((user != null) && !user.getPassword().equals(password))) {
309				ErrorMessage errMsg = new ErrorMessage();
310				errMsg.add("User Doesnot Exist.");
311				request.setAttribute("error", errMsg);
312				WebHelper.forward(request, response, AppConstants.SHOW_SIGNIN);
313			} else {
314				HttpSession session = request.getSession();
315				session.setAttribute("isSessionActive", true);
316				session.setAttribute("user", user.getEmail());
317
318				// forward User to home
319				WebHelper.forward(request, response, AppConstants.SHOW_HOME);
320			}
321		} catch (SQLException sqlex) {
322			throw new ServletException(sqlex);
323		}
324	}
325
326	/*
327	 * Handle User profile updates
328	 */
329	private void handleUpdateProfile(HttpServletRequest request,
330			HttpServletResponse response) throws ServletException, IOException {
331		ErrorMessage errMsg = new ErrorMessage();
332
333		// validate User existence
334		String email = request.getParameter("user_email");
335		String password = request.getParameter("user_current_password");
336		User user = null;
337		try {
338			user = Dao.getUser(email);
339		} catch (SQLException sqlex) {
340			throw new ServletException(sqlex);
341		}
342		if (user == null
343				|| ((user != null) && !user.getPassword().equals(password))) {
344			errMsg.add(AppConstants.USER_PSW_INCORRECT);
345		}
346
347		// Set credit card details for display
348		HttpSession session = request.getSession(false);
349		String useremail = (String) session.getAttribute("user");
350		User userFromSession = null;
351		try {
352			userFromSession = Dao.getUser(useremail);
353		} catch (SQLException sqlex) {
354			throw new ServletException(sqlex);
355		}
356		CreditCardDetail cardDetail = getCreditCardDetail(request, response,
357				userFromSession);
358		request.setAttribute("cardDetail", cardDetail);
359
360		// Check for password matching
361		String update_password = request.getParameter("update_password") != "" ? request
362				.getParameter("update_password") : AppConstants.EMPTY_STRING;
363		String update_password_confirmation = request
364				.getParameter("update_password_confirmation") != "" ? request
365				.getParameter("update_password_confirmation")
366				: AppConstants.EMPTY_STRING;
367		if (!update_password.equals(update_password_confirmation)) {
368			errMsg.add(AppConstants.PASSWORD_NOT_MATCH);
369		}
370
371		// If error exist , display in UI
372		if (errMsg.getMessageList().size() > 0) {
373			request.setAttribute("error", errMsg);
374			WebHelper.forward(request, response, AppConstants.SHOW_PROFILE);
375		} else {
376			updateProfile(request, response, user, update_password_confirmation);
377		}
378	}
379
380	/*
381	 * Update User profile
382	 */
383	private void updateProfile(HttpServletRequest request,
384			HttpServletResponse response, User user,
385			String update_password_confirmation) throws ServletException,
386			IOException {
387
388		// Do a profile update
389		try {
390
391			// create credit card and update User table with new
392			// creditcardId and new password
393			CreditCard newCreditCard = AppHelper.createCreditCard(request);
394			user.setCreditCardId(newCreditCard.getId());
395			user.setPassword(update_password_confirmation);
396			Dao.updateUser(user);
397		} catch (PayPalRESTException pex) {
398			if (pex.getMessage().contains(AppConstants.VALIDATION_ERROR)) {
399				WebHelper.formErrorMessage(request, pex);
400				WebHelper.forward(request, response, AppConstants.SHOW_PROFILE);
401				return;
402			} else {
403				LoggingManager.debug(PaymentServlet.class, pex.getMessage());
404				throw new ServletException(pex);
405			}
406		} catch (SQLException sqlex) {
407			throw new ServletException(sqlex);
408		}
409		WebHelper.forward(request, response, AppConstants.SHOW_HOME);
410	}
411
412}